const express = require("express");
const authRequiredMiddleware
 = require("../middleware/authRequired.middleware");
const authService=require("../services/auth.service")
const router = express.Router();

const {
  mapLoginRequestToLoginInput,
  mapLoginResultToResponse,
} = require("../adapters/responses/login.adapter");
const {
  mapRegisterRequestToRegisterInput,
  mapRegisterResultToResponse,
} = require("../adapters/responses/register.adapter");
const {
  mapMeRequestToUserId,
  mapMeResultToResponse,
} = require("../adapters/responses/me.adapter");


router.post("/register", async (req, res) => {
  try {
    const input = mapRegisterRequestToRegisterInput(req.body);
    const result = await authService.register(input);
    res.json(mapRegisterResultToResponse(result));
  } catch (err) {
    const status = err.statusCode || 500;
    res.status(status).json({
      message: err.message || "Kayıt işlemi başarısız.",
    });
  }
});


router.post("/login", async (req, res) => {
  try {
    const input = mapLoginRequestToLoginInput(req.body);
    const result = await authService.login(input);
    res.json(mapLoginResultToResponse(result));
  } catch (err) {
    const status = err.statusCode || 500;
    res.status(status).json({ message: err.message || "Giriş işlemi başarısız." });
  }
});



router.get("/me", authRequiredMiddleware
, async (req, res) => {
  try {
    const userId = mapMeRequestToUserId(req);
    const user = await authService.getMe(userId);
    res.json(mapMeResultToResponse(user));
  } catch (err) {
    const status = err.statusCode || 500;
    res.status(status).json({
      message: err.message || "Sunucu hatası",
    });
  }
});
module.exports = router;
