import { Router } from "express";
import { AuthHandler } from "../../handlers/AuthHandler.js";
import { UserRepository } from "../../repositories/UserRepository.js";
import { UserDtoEntityMapper } from "../../mappers/UserDtoEntityMapper.js";
import {
  ValidationError,
  UnauthorizedError,
  InternalServerError,
} from "../errors/httpErrors.js";
import { LoginRequest } from "../dtos/LoginRequest.js";

export const  authBasicRoute = "/auth"

const router = Router();
const userRepository = new UserRepository();
const mapper = new UserDtoEntityMapper();
const authController = new AuthHandler(userRepository, mapper);

/**
 * Login using username and password
 * Consumes LoginRequest
 * Responds with LoginResponse
 */
router.post("/login", async (req, res) => {
    console.log("login point called")
  try {
    const requestDto: LoginRequest = req.body;
    const responseDto = await authController.login(requestDto);
    res.json(responseDto);
  } catch (err: any) {
    if (err instanceof ValidationError || err instanceof UnauthorizedError) {
      res.status(err.statusCode).json({ error: err.message });
    } else {
      console.error("Unexpected error:", err);
      const internalError = new InternalServerError("Unexpected error");
      res.status(internalError.statusCode).json({ error: internalError.message });
    }
  }
});

export default router;
