import { Request, Response } from 'express';

import * as roleService from '@/modules/roles/roles.service';
import catchAsync from '@/shared/utils/catchAsync';
import responseCodes from '@/shared/utils/responseCode/responseCode';
import { pick } from '@/shared/utils';

const { RoleResponseCodes } = responseCodes;

export const createRole = catchAsync(async (req: Request, res: Response) => {
  const role = await roleService.createRole(req.body);
  res.success(role, RoleResponseCodes.SUCCESS, 'Role Created Successfully');
});

export const updateRole = catchAsync(async (req: Request, res: Response) => {
  const { id } = pick(req.params, ['id']);
  const { name, description, company} = req.body;

  const updatedRole = await roleService.updateRole({
    name,
    description,
    company,
    id,
  });
  res.success(
    updatedRole,
    RoleResponseCodes.SUCCESS,
    'Role Updated Successfully',
  );
});

export const deleteRoleById = catchAsync(
  async (req: Request, res: Response) => {
    const { id } = pick(req.params, ['id']);

    const role = await roleService.deleteRole(id);
    res.success(role, RoleResponseCodes.SUCCESS, 'Role Deleted Successfully');
  },
);

export const getRoleById = catchAsync(async (req: Request, res: Response) => {
  const { id } = pick(req.params, ['id']);

  const roles = await roleService.getRoleById(id);

  res.success(roles, RoleResponseCodes.SUCCESS, 'Role Fetched Successfully');
});

export const getRoles = catchAsync(async (req: Request, res: Response) => {
  const companyId = req.user?.company?.id;
  const filter = {
    ...pick(req.query, ['search']),
    ...(companyId && { company: companyId }),
  };
  const options = pick(req.query, [
    'sortBy',
    'limit',
    'page',
    'includeTimeStamps',
  ]);

  const roles = await roleService.queryRoles(filter, options);

  res.success(roles, RoleResponseCodes.SUCCESS, 'Role Fetched Successfully');
});
