import { PipelineStage } from 'mongoose';

export const monthNameArray = [
  '',
  'Jan',
  'Feb',
  'Mar',
  'Apr',
  'May',
  'Jun',
  'Jul',
  'Aug',
  'Sep',
  'Oct',
  'Nov',
  'Dec',
];

export const getAddDateFieldsPipeline = (): PipelineStage[] => [
  {
    $addFields: {
      monthNum: { $month: '$createdAt' },
      year: { $year: '$createdAt' },
    },
  },
  {
    $addFields: {
      month: {
        $arrayElemAt: [monthNameArray, '$monthNum'],
      },
    },
  },
];

export const getLeadStageBreakdownPipeline = (
  baseMatch: object,
): PipelineStage[] => [
  { $match: baseMatch },
  {
    $group: {
      _id: '$leadStage',
      count: { $sum: 1 },
    },
  },
  {
    $lookup: {
      from: 'leadstages',
      localField: '_id',
      foreignField: '_id',
      as: 'stage',
    },
  },
  { $unwind: '$stage' },
  {
    $project: {
      leadStageId: '$_id',
      stageName: '$stage.stageName',
      stageColor: '$stage.color',
      position: '$stage.position',
      count: 1,
      _id: 0,
    },
  },
  {
    $sort: {
      position: 1,
    },
  },
  {
    $group: {
      _id: null,
      totalCount: { $sum: '$count' },
      stages: { $push: '$$ROOT' },
    },
  },
  {
    $addFields: {
      topStage: {
        $reduce: {
          input: '$stages',
          initialValue: {
            stageName: '',
            count: 0,
          },
          in: {
            $cond: [
              { $gt: ['$$this.count', '$$value.count'] },
              { stageName: '$$this.stageName', count: '$$this.count' },
              '$$value',
            ],
          },
        },
      },
    },
  },
  {
    $project: {
      _id: 0,
      stages: 1,
      totalCount: 1,
      topStageName: '$topStage.stageName',
      topStageCount: '$topStage.count',
    },
  },
];

export const getMonthlyLeadTotalsPipeline = (
  baseMatch: object,
): PipelineStage[] => [
  { $match: baseMatch },
  ...getAddDateFieldsPipeline(),
  {
    $group: {
      _id: {
        year: '$year',
        monthNum: '$monthNum',
        month: '$month',
      },
      count: { $sum: 1 },
    },
  },
  {
    $project: {
      _id: 0,
      year: '$_id.year',
      month: '$_id.month',
      monthNum: '$_id.monthNum',
      leads: '$count',
    },
  },
  { $sort: { year: 1, monthNum: 1 } }, // ✅ Proper sort keys
];

export const getConversionRatePipeline = (
  baseMatch: object,
): PipelineStage[] => [
  { $match: baseMatch },
  ...getAddDateFieldsPipeline(),
  {
    $group: {
      _id: {
        year: '$year',
        monthNum: '$monthNum',
        month: '$month',
      },
      total: { $sum: 1 },
      won: {
        $sum: {
          $cond: [{ $eq: ['$leadStageKey', 'Lead Won'] }, 1, 0],
        },
      },
    },
  },
  {
    $project: {
      _id: 0,
      year: '$_id.year',
      month: '$_id.month',
      monthNum: '$_id.monthNum',
      total: 1,
      won: 1,
      conversionRate: {
        $cond: [
          { $eq: ['$total', 0] },
          0,
          { $multiply: [{ $divide: ['$won', '$total'] }, 100] },
        ],
      },
    },
  },
  { $sort: { year: 1, monthNum: 1 } }, 
];

export const getLeadScoreBucketPipeline = (
  baseMatch: object,
): PipelineStage[] => [
  { $match: baseMatch },
  {
    $bucket: {
      groupBy: '$leadScore',
      boundaries: [0, 50, 75, 101],
      default: 'Unknown',
      output: { count: { $sum: 1 } },
    },
  },
  {
    $project: {
      _id: 0,
      label: {
        $switch: {
          branches: [
            { case: { $eq: ['$_id', 0] }, then: 'low' }, // 0–49
            { case: { $eq: ['$_id', 50] }, then: 'medium' }, // 50–74
            { case: { $eq: ['$_id', 75] }, then: 'high' }, // 75–100
          ],
          default: 'Unknown',
        },
      },
      count: 1,
    },
  },
];
