import { Request, Response } from 'express';

import * as permissionService from '@/modules/permissions/permissions.service';
import catchAsync from '@/shared/utils/catchAsync';
import responseCodes from '@/shared/utils/responseCode/responseCode';
import { pick } from '@/shared/utils';
import { getObjectId } from '@/shared/utils/commonHelper';

const { PermissionResponseCodes } = responseCodes;

export const createPermission = catchAsync(
  async (req: Request, res: Response) => {
    const { roleId } = pick(req.query, ['roleId']);
    const companyId = getObjectId(req.user.company?.id);
    const permission = await permissionService.addOrUpdatePermission(
      companyId,
      roleId,
      req.body,
    );
    res.success(
      permission,
      PermissionResponseCodes.SUCCESS,
      'Permission Created Successfully',
    );
  },
);

export const getRoleWithPermissions = catchAsync(
  async (req: Request, res: Response) => {
    const { roleId, companyType } = pick(req.query, ['roleId', 'companyType']);
    const companyId = req.user.company?.id;

    const permissions = await permissionService.getRoleWithPermissions(
      companyId,
      roleId,
      companyType,
    );

    res.success(
      permissions,
      PermissionResponseCodes.SUCCESS,
      'Permission Fetched Successfully',
    );
  },
);
