import { Request, Response } from 'express';
import * as leadScoreConfigService from './leadScore.service';
import catchAsync from '@/shared/utils/catchAsync';
import responseCodes from '@/shared/utils/responseCode/responseCode';
import { pick } from '@/shared/utils';

const { LeadScoreResponseCodes } = responseCodes;

export const createLeadScoreConfig = catchAsync(async (req: Request, res: Response) => {
  const { company } = req.user;
  const companyId = company?.id;

  const config = await leadScoreConfigService.createLeadScoreConfig({
    ...req.body,
    companyId,
    createdBy: req.user.id,
  });

  res.success(
    config,
    LeadScoreResponseCodes.SUCCESS,
    'Lead Score Config Created Successfully',
  );
});

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

  const config = await leadScoreConfigService.updateLeadScoreConfig(id, {
    ...req.body,
    updatedBy: req.user.id,
  });

  res.success(
    config,
    LeadScoreResponseCodes.SUCCESS,
    'Lead Score Config Updated Successfully',
  );
});

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

  res.success(
    config,
    LeadScoreResponseCodes.SUCCESS,
    'Lead Score Config Fetched Successfully',
  );
});

export const getLeadScoreConfigs = catchAsync(async (req: Request, res: Response) => {
  const filter = pick(req.query, ['companyId']);
  const options = pick(req.query, ['sortBy', 'limit', 'page', 'fields', 'populate']);

  req.user.company &&
    filter.companyId === undefined &&
    (filter.companyId = req.user.company.id);

  const configs = await leadScoreConfigService.queryLeadScoreConfigs(filter, options);

  res.success(
    configs,
    LeadScoreResponseCodes.SUCCESS,
    'Lead Score Configs Fetched Successfully',
  );
});

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

  res.success(
    true,
    LeadScoreResponseCodes.SUCCESS,
    'Lead Score Config Deleted Successfully',
  );
});
