import { Request, Response } from "express";

import { AuthService } from "./auth.service";

const authService = new AuthService();

export class AuthController {

    async login (
        req:Request,
        res:Response
    ){
        try {

            const {
                userName,
                password
            } = req.body;
            

            //Validar datos de entrada
            if(!userName || !password){
                return res.status(400).json({
                    message:"Usuario y contraseña son requeridos"
                });
            }

            const result = await authService.login(
                userName,
                password
            );

            res.json(result);

        } catch(error:any){

            res.status(401).json({
                message:error.message
            });

        }
    }

    async logout(
        req:Request,
        res:Response
    ){
        try{

            const user = (req as any).user;
            const result = await authService.logout(user.id);
            res.json(result);

        }catch(error) {
            res.status(500).json({
                message:"Error al cerrar sesión",
                error
            });
        }
    }
}