import { Request, Response } from "express";

import { RoleService } from "./role.service";

const roleService = new RoleService();

export class RoleController {

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

        res.json(roles);

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

        }
    }

    async getById(
        req:Request,
        res:Response
    ){
        try{
        const role = await roleService.getById(
            req.params.id as string
        );
        res.json(role);
    
        }catch(error){
            res.status(500).json({
                message:"Error al obtener roles",
                error
            })

        }

    }

    async create(

        req:Request,
        res:Response
    ){
        try
        {
            const role = await roleService.create(
                req.body
            );

            res.status(201).json(role);

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

        }
    }

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

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

            res.status(200).json(role);
        } catch(error) {
            res.status(500).json({
                message:"Error al actualizar rol"
            });

        }
    }

    async delete (
        req:Request,
        res:Response
    ){
        try{
            const role = await roleService.delete(
                req.params.id as string
            )

            if(!role){
                return res.status(404).json({
                    message:"Role no encontrado"
                });
            }
            res.json({
                message:"Rol eliminado correctamente"
            });

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

        }
    }
}