import { Request, Response } from "express";
import { UserService } from "./user.service";

const userService = new UserService();

export class UserController {

    async getAll(
        req:Request,
        res:Response
    ) {
        try {
        const users = await userService.getAll();

        res.json(users);

        }catch(error){
            res.status(500).json({
                message:"Error al obtener usuarios",
                error
            });

        }
    }

    async getById(
        req:Request,
        res:Response
    ){
        try {
        
            const user = await userService.getById(
            req.params.id as string
        );

        if (!user) {
            return res.status(404).json({
                message: "Usuario no encontrado"
            });
        }

        res.json(user);

        } catch(error) {
            res.status(500).json({
                message:"Error al obtener usuarios",
                error
            });
        }
    }

    async create (
        req:Request,
        res:Response
    ) {
        try {
            const user =
            await userService.create(
                req.body
            );
            res.status(201).json(user);

        }catch(error){
            res.status(500).json({
                message:"Error al crear usuario",
                error
            });

        }
    }

    async update(
        req:Request,
        res:Response
    ){
        try{
            const user =
            await userService.update(
                req.params.id as string,
                req.body
            );

            if(!user){
                return res.status(404).json({
                    message:"Usuario no encontrado"
                });
            }
            res.status(200).json(user);
        }catch(error){
            res.status(500).json({
                message:"Error al actualizar usuario",
                error
            })
        }
    }

    async delete (
        req:Request,
        res:Response
    ) {

        try{
            const user = await userService.delete(
                req.params.id as string
            );

            if (!user){
                return res.status(404).json({
                    message:"Usuario no encontrado"
                });
            }

            res.json({
                message: "Usuario eliminado"});

        }catch(error){
            res.status(500).json({
                message:"Error al eliminar usuario",
                error
            });
        }
    }
    
}