import { Request, Response } from 'express';
import * as leadStageService from '@/modules/master/leadStage/leadStage.service';
import catchAsync from '@/shared/utils/catchAsync';
import responseCodes from '@/shared/utils/responseCode/responseCode';
import { pick } from '@/shared/utils';
const { LeadStageResponseCodes } = responseCodes;
import { UserType } from '@/shared/constants/enum.constant';

export const createLeadStage = catchAsync(async (req: Request, res: Response) => {
  if (req.user.userType === UserType.SUPERADMIN) {
    req.body.isDefault = true;

    const stageName = String(req.body.stageName || '').trim().toLowerCase();
    if (stageName === 'lead won' || stageName === 'lead lost') 
      req.body.isProtected = true;
  }

  if (req.user.company) 
    req.body.company = req.user.company.id;
  
  const leadStage = await leadStageService.createLeadStage(req.body);
  res.success(
    leadStage,
    LeadStageResponseCodes.SUCCESS,
    'Lead Stage Created Successfully',
  );
});

export const getLeadStages = catchAsync(async (req: Request, res: Response) => {
  const filter = pick(req.query, ['companyId', 'isActive', 'company']);
  const options = pick(req.query, ['sortBy', 'limit', 'page', 'fields', 'populate', 'includeTimeStamps', 'alias']);
  const { search, company } = req.query;

  filter.isDefault = false;

  const userCompanyId = req.user?.company?.id;

  if (req.user.userType === UserType.SUPERADMIN && !company) 
    filter.isDefault = true;
   else 
    filter.company = company || userCompanyId;
  

  if (typeof search === 'string' && search.trim()) 
    filter.$or = [
      { stageName: { $regex: search, $options: 'i' } },
      { description: { $regex: search, $options: 'i' } },
    ];
  

  const leadStages = await leadStageService.queryLeadStages(filter, options);

  res.success(leadStages, LeadStageResponseCodes.SUCCESS, 'Lead Stages Fetched Successfully');
});


export const updateLeadStage = catchAsync(async (req: Request, res: Response) => {
  const { id } = pick(req.params, ['id']);
  const updatedLeadStage = await leadStageService.updateLeadStage(id, req.body);
  res.success(updatedLeadStage, LeadStageResponseCodes.SUCCESS, 'Lead Stage Updated Successfully');
});

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

  const leadStage = await leadStageService.deleteLeadStage(id);
  res.success(leadStage, LeadStageResponseCodes.SUCCESS, 'Lead Stage Deleted Successfully');
});

export const updateLeadStagesPosition = catchAsync(async (req: Request, res: Response) => {
  await leadStageService.updateLeadStagesPosition(req.body);
  res.success(null, LeadStageResponseCodes.SUCCESS, 'Lead Stage Positions Updated Successfully');
});