import { FastifyRequest, FastifyReply } from 'fastify';

export const getRoles = async (request: FastifyRequest, reply: FastifyReply) => {
    try {
        const roles = await request.server.prisma.role.findMany({
            orderBy: {
                name: 'asc',
            },
            include: {
                _count: {
                    select: { users: true }
                }
            }
        });
        return roles;
    } catch (error) {
        request.log.error(error);
        return reply.code(500).send({ message: 'Failed to fetch roles' });
    }
};

export const createRole = async (request: FastifyRequest, reply: FastifyReply) => {
    const data = request.body as any;

    try {
        const role = await request.server.prisma.role.create({
            data: {
                name: data.name,
                description: data.description,
                permissions: data.permissions || {},
            },
        });

        return reply.code(201).send(role);
    } catch (error) {
        request.log.error(error);
        return reply.code(500).send({ message: 'Failed to create role' });
    }
};

export const updateRole = async (request: FastifyRequest, reply: FastifyReply) => {
    const { id } = request.params as { id: string };
    const data = request.body as any;

    try {
        const role = await request.server.prisma.role.update({
            where: { id },
            data: {
                name: data.name,
                description: data.description,
                permissions: data.permissions,
            },
        });

        return role;
    } catch (error) {
        request.log.error(error);
        return reply.code(500).send({ message: 'Failed to update role' });
    }
};

export const deleteRole = async (request: FastifyRequest, reply: FastifyReply) => {
    const { id } = request.params as { id: string };

    try {
        // Check if system role
        const role = await request.server.prisma.role.findUnique({ where: { id } });
        if (role?.isSystem) {
            return reply.code(403).send({ message: 'Cannot delete system role' });
        }

        await request.server.prisma.role.delete({
            where: { id },
        });

        return reply.code(204).send();
    } catch (error) {
        request.log.error(error);
        return reply.code(500).send({ message: 'Failed to delete role' });
    }
};
