import { getObjectId } from '@/shared/utils/commonHelper';
import { PipelineStage, Types } from 'mongoose';

export type SalesSummaryReportView = 'overview' | 'detail' | 'all';

type BuildSalesSummaryBasePipelineParams = {
  companyId: string | Types.ObjectId;
  isBrokerCompany: boolean;
  startDate?: string;
  endDate?: string;
  selectedEntityIds: Types.ObjectId[];
  selectedSourceIds: Types.ObjectId[];
};

const buildSalesSummaryMatchStage = ({
  isBrokerCompany,
  startDate,
  endDate,
  selectedEntityIds,
}: Omit<BuildSalesSummaryBasePipelineParams, 'companyId' | 'selectedSourceIds'>) => {
  const matchStage: Record<string, unknown> = {
    action: 'book',
  };

  if (startDate || endDate) {
    const createdAt: Record<string, Date> = {};
    if (startDate) createdAt.$gte = new Date(startDate);
    if (endDate) createdAt.$lte = new Date(endDate);
    if (Object.keys(createdAt).length) matchStage.createdAt = createdAt;
  }

  if (selectedEntityIds.length > 0) {
    const entityField = isBrokerCompany ? 'property' : 'project';
    matchStage[entityField] =
      selectedEntityIds.length === 1
        ? selectedEntityIds[0]
        : { $in: selectedEntityIds };
  }

  return matchStage;
};

export const buildSalesSummaryBasePipeline = ({
  companyId,
  isBrokerCompany,
  startDate,
  endDate,
  selectedEntityIds,
  selectedSourceIds,
}: BuildSalesSummaryBasePipelineParams): PipelineStage[] => {
  const matchStage = buildSalesSummaryMatchStage({
    isBrokerCompany,
    startDate,
    endDate,
    selectedEntityIds,
  });

  return [
    { $match: matchStage },
    {
      $lookup: {
        from: 'leads',
        localField: 'lead',
        foreignField: '_id',
        as: 'leadInfo',
      },
    },
    { $unwind: { path: '$leadInfo', preserveNullAndEmptyArrays: true } },
    {
      $match: {
        'leadInfo.company': getObjectId(companyId),
        ...(selectedSourceIds.length > 0
          ? {
              'leadInfo.source':
                selectedSourceIds.length === 1
                  ? selectedSourceIds[0]
                  : { $in: selectedSourceIds },
            }
          : {}),
      },
    },
    {
      $lookup: {
        from: 'projects',
        localField: 'project',
        foreignField: '_id',
        as: 'projectInfo',
      },
    },
    { $unwind: { path: '$projectInfo', preserveNullAndEmptyArrays: true } },
    {
      $lookup: {
        from: 'individualproperties',
        localField: 'property',
        foreignField: '_id',
        as: 'propertyInfo',
      },
    },
    { $unwind: { path: '$propertyInfo', preserveNullAndEmptyArrays: true } },
    {
      $lookup: {
        from: 'units',
        localField: 'unit',
        foreignField: '_id',
        as: 'unitInfo',
      },
    },
    { $unwind: { path: '$unitInfo', preserveNullAndEmptyArrays: true } },
    {
      $lookup: {
        from: 'sources',
        localField: 'leadInfo.source',
        foreignField: '_id',
        as: 'sourceInfo',
      },
    },
    { $unwind: { path: '$sourceInfo', preserveNullAndEmptyArrays: true } },
    {
      $addFields: {
        propertyDealValue: {
          $cond: [
            {
              $in: [
                '$propertyInfo.listingType',
                ['rent', 'lease', 'preLeased'],
              ],
            },
            {
              $ifNull: [
                '$propertyInfo.monthlyRent',
                {
                  $ifNull: ['$propertyInfo.totalPrice', '$propertyInfo.price'],
                },
              ],
            },
            {
              $ifNull: [
                '$propertyInfo.totalPrice',
                {
                  $ifNull: ['$propertyInfo.price', '$propertyInfo.monthlyRent'],
                },
              ],
            },
          ],
        },
        entityName: {
          $cond: [
            isBrokerCompany,
            { $ifNull: ['$propertyInfo.title', '$projectInfo.projectName'] },
            { $ifNull: ['$projectInfo.projectName', '$propertyInfo.title'] },
          ],
        },
        entityId: {
          $cond: [
            isBrokerCompany,
            { $ifNull: ['$property', '$project'] },
            { $ifNull: ['$project', '$property'] },
          ],
        },
        customerNameResolved: {
          $ifNull: ['$leadInfo.contactDetails.name', 'Unknown'],
        },
        totalUnitPrice: {
          $ifNull: [
            '$unitInfo.price',
            {
              $ifNull: [
                '$propertyDealValue',
                { $ifNull: ['$bookingAmount', 0] },
              ],
            },
          ],
        },
      },
    },
  ];
};

export const buildSalesSummaryAnalyticsPipeline = (
  basePipeline: PipelineStage[],
): PipelineStage[] => [
  ...basePipeline,
  {
    $group: {
      _id: null,
      totalSalesValue: { $sum: '$totalUnitPrice' },
      amountCollected: { $sum: '$bookingAmount' },
      totalBookedUnits: { $sum: 1 },
    },
  },
];

export const buildSalesSummaryPieChartPipeline = (
  basePipeline: PipelineStage[],
): PipelineStage[] => [
  ...basePipeline,
  {
    $group: {
      _id: '$entityId',
      name: { $first: '$entityName' },
      value: { $sum: '$totalUnitPrice' },
    },
  },
  { $match: { name: { $ne: null } } },
  { $sort: { value: -1 } },
];

export const buildSalesSummaryBarChartPipeline = (
  basePipeline: PipelineStage[],
): PipelineStage[] => [
  ...basePipeline,
  {
    $group: {
      _id: '$sourceInfo._id',
      source: { $first: '$sourceInfo.name' },
      value: { $sum: '$totalUnitPrice' },
    },
  },
  { $match: { source: { $ne: null } } },
  { $sort: { value: -1 } },
];

export const buildSalesSummaryLineChartPipeline = (
  basePipeline: PipelineStage[],
): PipelineStage[] => [
  ...basePipeline,
  {
    $group: {
      _id: {
        year: { $year: '$createdAt' },
        month: { $month: '$createdAt' },
      },
      sales: { $sum: '$totalUnitPrice' },
      count: { $sum: 1 },
    },
  },
  { $sort: { '_id.year': 1, '_id.month': 1 } },
  {
    $project: {
      month: {
        $concat: [
          {
            $switch: {
              branches: [
                { case: { $eq: ['$_id.month', 1] }, then: 'Jan' },
                { case: { $eq: ['$_id.month', 2] }, then: 'Feb' },
                { case: { $eq: ['$_id.month', 3] }, then: 'Mar' },
                { case: { $eq: ['$_id.month', 4] }, then: 'Apr' },
                { case: { $eq: ['$_id.month', 5] }, then: 'May' },
                { case: { $eq: ['$_id.month', 6] }, then: 'Jun' },
                { case: { $eq: ['$_id.month', 7] }, then: 'Jul' },
                { case: { $eq: ['$_id.month', 8] }, then: 'Aug' },
                { case: { $eq: ['$_id.month', 9] }, then: 'Sep' },
                { case: { $eq: ['$_id.month', 10] }, then: 'Oct' },
                { case: { $eq: ['$_id.month', 11] }, then: 'Nov' },
                { case: { $eq: ['$_id.month', 12] }, then: 'Dec' },
              ],
              default: '',
            },
          },
          ' ',
          { $toString: '$_id.year' },
        ],
      },
      sales: 1,
      count: 1,
    },
  },
];

export const buildSalesSummaryDetailedListPipeline = (
  basePipeline: PipelineStage[],
): PipelineStage[] => [
  ...basePipeline,
  {
    $project: {
      id: '$_id',
      bookingDate: {
        $dateToString: { format: '%Y-%m-%d', date: '$createdAt' },
      },
      projectName: '$entityName',
      unitNumber: { $ifNull: ['$unitInfo.unitNumber', '-'] },
      customerName: '$customerNameResolved',
      totalUnitPrice: '$totalUnitPrice',
      bookingAmount: '$bookingAmount',
      source: '$sourceInfo.name',
      leadId: '$lead',
      projectId: '$entityId',
      unitId: '$unit',
    },
  },
  { $sort: { bookingDate: -1 } },
];
