import { Lead } from '@/modules/lead/lead.model';
import { getObjectId } from '@/shared/utils/commonHelper';

export async function getOverview(companyId: string, fromISO: string, toISO: string) {
  const from = new Date(fromISO);
  const to = new Date(toISO);

  const [totalLeadsAgg] = await Lead.aggregate([
    { $match: { company: getObjectId(companyId), createdAt: { $gte: from, $lte: to } } },
    { $count: 'totalLeads' },
  ]);

  const totalLeads = totalLeadsAgg?.totalLeads ?? 0;

  const activeIntegrationsAgg = await Lead.aggregate([
    { $match: { company: getObjectId(companyId), createdAt: { $gte: from, $lte: to } } },
    { $group: { _id: '$captureLead' } },
    { $count: 'count' },
  ]);
  const activeIntegrations = activeIntegrationsAgg?.[0]?.count ?? 0;

  return { totalLeads, activeIntegrations, period: { from: fromISO, to: toISO } };
}

export async function getPlatformTimeseries(companyId: string, fromISO: string, toISO: string) {
  const from = new Date(fromISO);
  const to = new Date(toISO);

  const rows = await Lead.aggregate([
    { $match: { company: getObjectId(companyId), createdAt: { $gte: from, $lte: to } } },
    { $lookup: { from: 'captureleads', localField: 'captureLead', foreignField: '_id', as: 'cl' } },
    { $unwind: '$cl' },
    { $project: { platform: '$cl.platform', x: { $dateToString: { format: '%Y-%m-%d', date: '$createdAt' } } } },
    { $group: { _id: { platform: '$platform', x: '$x' }, y: { $sum: 1 } } },
    { $project: { platform: '$_id.platform', x: '$_id.x', y: 1, _id: 0 } },
    { $sort: { platform: 1, x: 1 } },
  ]);

  const byPlatform = new Map<string, Array<{ x: string; y: number }>>();
  for (const r of rows as Array<{ platform: string; x: string; y: number }>) {
    if (!byPlatform.has(r.platform)) byPlatform.set(r.platform, []);
    byPlatform.get(r.platform)!.push({ x: r.x, y: r.y });
  }

  const series = Array.from(byPlatform.entries()).map(([platform, points]) => ({ platform, points }));
  return { granularity: 'day' as const, series };
}
