import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
import { DealStage, LeadStatus, UserRole, UserStatus } from '@prisma/client';
import PDFDocument from 'pdfkit';
import { PrismaService } from '../../prisma/prisma.service';
import { RequestTenantContext, TenantQueryHelper } from '../../common/tenancy/tenant-query.helper';
import { computeDaysInStage, computeWeightedAmount } from '../deals/deal.helper';
import { DEAL_STAGES, OPEN_DEAL_STAGES } from '../deals/deal.constants';
import { LEAD_SOURCES } from '../leads/lead.constants';
import { validateReportShape } from './custom-report.constants';
import { ExportCustomReportDto } from './dto/export-custom-report.dto';
import { SaveCustomReportDto, UpdateCustomReportDto } from './dto/save-custom-report.dto';
import { DashboardQuery } from './dto/get-dashboard.query';

const NOT_SPECIFIED = 'Not specified';
const MONTH_NAMES = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

@Injectable()
export class DashboardService {
  constructor(
    private readonly prisma: PrismaService,
    private readonly tenant: TenantQueryHelper,
  ) {}

  // Resolves the starting timestamp based on selected period view.
  private getPeriodStart(period: 'month' | 'quarter' | 'year' = 'month'): Date {
    const now = new Date();
    if (period === 'year') {
      return new Date(now.getFullYear(), 0, 1);
    }
    if (period === 'quarter') {
      const currentQuarterMonth = Math.floor(now.getMonth() / 3) * 3;
      return new Date(now.getFullYear(), currentQuarterMonth, 1);
    }
    return new Date(now.getFullYear(), now.getMonth(), 1);
  }

  // Returns aggregated dashboard statistics and high-priority action items.
  async getDashboard(ctx: RequestTenantContext, queryOrPeriod?: DashboardQuery | string) {
    const tenantId = this.tenant.getRequiredTenantId(ctx);
    const { start: periodStart, end: periodEnd, periodKey, periodLabel } = this.resolveQueryDates(queryOrPeriod || 'today');
    const now = new Date();
    const todayEnd = new Date(now);
    todayEnd.setHours(23, 59, 59, 999);
    const sevenDaysAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
    const twelveMonthsAgo = new Date(now.getFullYear(), now.getMonth() - 11, 1);

    const [openDeals, wonDealsInPeriod, lostDealsInPeriod, newLeadsCount, qualifiedLeadsCount, leadSourceGroups, todayTasks, attentionDeals, activeProjects, recentTimes, recentActivities, pastWonDealsYear, repsLeaderboardUsers] = await Promise.all([
      this.prisma.deal.findMany({
        where: this.tenant.scopeWhere(ctx, { stage: { in: [...OPEN_DEAL_STAGES] } }),
        select: { id: true, stage: true, amount: true, title: true, dealNumber: true, stageChangedAt: true, closeDate: true, account: { select: { id: true, name: true } }, owner: { select: { id: true, name: true } } },
      }),
      this.prisma.deal.findMany({
        where: this.tenant.scopeWhere(ctx, {
          stage: DealStage.CLOSED_WON,
          OR: [{ closedAt: { gte: periodStart, lte: periodEnd } }, { closeDate: { gte: periodStart, lte: periodEnd } }],
        }),
        select: { amount: true },
      }),
      this.prisma.deal.findMany({
        where: this.tenant.scopeWhere(ctx, {
          stage: DealStage.CLOSED_LOST,
          OR: [{ closedAt: { gte: periodStart, lte: periodEnd } }, { closeDate: { gte: periodStart, lte: periodEnd } }],
        }),
        select: { amount: true },
      }),
      this.prisma.lead.count({
        where: this.tenant.scopeWhere(ctx, { createdAt: { gte: periodStart, lte: periodEnd } }),
      }),
      this.prisma.lead.count({
        where: this.tenant.scopeWhere(ctx, { status: LeadStatus.QUALIFIED, createdAt: { gte: periodStart, lte: periodEnd } }),
      }),
      this.prisma.lead.groupBy({
        by: ['source'],
        where: this.tenant.scopeWhere(ctx, { createdAt: { gte: periodStart, lte: periodEnd } }),
        _count: { id: true },
      }),
      this.prisma.task.findMany({
        where: this.tenant.scopeWhere(ctx, { completed: false, ownerId: ctx.userId, dueDate: { lte: todayEnd } }),
        take: 5,
        orderBy: [{ dueDate: 'asc' }, { createdAt: 'desc' }],
        select: { id: true, title: true, priority: true, dueDate: true, completed: true, deal: { select: { id: true, title: true } }, account: { select: { id: true, name: true } }, contact: { select: { id: true, name: true } }, lead: { select: { id: true, name: true } }, project: { select: { id: true, name: true } } },
      }),
      this.prisma.deal.findMany({
        where: this.tenant.scopeWhere(ctx, { stage: { in: [...OPEN_DEAL_STAGES] } }),
        take: 5,
        orderBy: [{ stageChangedAt: 'asc' }, { createdAt: 'asc' }],
        select: { id: true, title: true, dealNumber: true, stage: true, amount: true, stageChangedAt: true, closeDate: true, account: { select: { id: true, name: true } } },
      }),
      this.prisma.project.findMany({
        where: { tenantId, status: { in: ['Planned', 'Active', 'On hold'] } },
        select: { id: true, name: true, targetEndDate: true, budgetHours: true, timeEntries: { select: { hours: true } } },
      }),
      this.prisma.timeEntry.findMany({
        where: { tenantId, date: { gte: sevenDaysAgo } },
        select: { hours: true, isBillable: true },
      }),
      this.prisma.activity.findMany({
        where: this.tenant.scopeWhere(ctx, { performedAt: { gte: periodStart, lte: periodEnd } }),
        take: 5,
        orderBy: [{ performedAt: 'desc' }, { id: 'desc' }],
        select: { id: true, type: true, title: true, performedAt: true, owner: { select: { id: true, name: true } }, lead: { select: { id: true, name: true } }, contact: { select: { id: true, name: true } }, account: { select: { id: true, name: true } }, deal: { select: { id: true, title: true } } },
      }),
      this.prisma.deal.findMany({
        where: this.tenant.scopeWhere(ctx, {
          stage: DealStage.CLOSED_WON,
          OR: [{ closedAt: { gte: twelveMonthsAgo } }, { closeDate: { gte: twelveMonthsAgo } }],
        }),
        select: { amount: true, closedAt: true, closeDate: true },
      }),
      this.prisma.user.findMany({
        where: this.tenant.scopeWhere(ctx, { status: UserStatus.ACTIVE }),
        select: {
          id: true,
          name: true,
          assignedDeals: {
            where: this.tenant.scopeWhere(ctx, {
              stage: DealStage.CLOSED_WON,
              OR: [{ closedAt: { gte: periodStart, lte: periodEnd } }, { closeDate: { gte: periodStart, lte: periodEnd } }],
            }),
            select: { amount: true, stage: true },
          },
        },
      }),
    ]);

    const openPipeline = openDeals.reduce((sum, d) => sum + Number(d.amount), 0);
    const weightedPipeline = openDeals.reduce((sum, d) => sum + computeWeightedAmount(Number(d.amount), d.stage), 0);
    const revenueWon = wonDealsInPeriod.reduce((sum, d) => sum + Number(d.amount), 0);

    const wonCount = wonDealsInPeriod.length;
    const lostCount = lostDealsInPeriod.length;
    const closedCount = wonCount + lostCount;
    const winRate = closedCount > 0 ? Math.round((wonCount / closedCount) * 100) : 0;
    const lostRevenue = lostDealsInPeriod.reduce((sum, d) => sum + Number(d.amount), 0);

    const stageBreakdown = DEAL_STAGES.map((st) => {
      if (st === DealStage.CLOSED_WON) {
        return { stage: st, count: wonCount, value: revenueWon };
      }
      if (st === DealStage.CLOSED_LOST) {
        return { stage: st, count: lostCount, value: lostRevenue };
      }
      const stageDeals = openDeals.filter((d) => d.stage === st);
      return {
        stage: st,
        count: stageDeals.length,
        value: stageDeals.reduce((sum, d) => sum + Number(d.amount), 0),
      };
    });

    const sourcesMap = new Map<string, number>();
    for (const group of leadSourceGroups) {
      const label = !group.source ? NOT_SPECIFIED : /^Other(:|$)/.test(group.source) ? 'Other' : group.source;
      sourcesMap.set(label, (sourcesMap.get(label) ?? 0) + group._count.id);
    }
    const leadSources = [...LEAD_SOURCES, ...(sourcesMap.has(NOT_SPECIFIED) ? [NOT_SPECIFIED] : [])].map((src) => ({
      source: src,
      count: sourcesMap.get(src) || 0,
    }));

    const atRiskProjectsCount = activeProjects.filter((p) => {
      const logged = p.timeEntries.reduce((s, t) => s + Number(t.hours), 0);
      const isPastDue = new Date(p.targetEndDate) < now;
      const budgetHours = Number(p.budgetHours);
      const isOverBudget = budgetHours > 0 && logged > budgetHours;
      return isPastDue || isOverBudget;
    }).length;

    const teamHoursThisWeek = recentTimes.reduce((sum, t) => sum + Number(t.hours), 0);
    const billableHoursThisWeek = recentTimes.filter((t) => t.isBillable).reduce((sum, t) => sum + Number(t.hours), 0);

    // 12-month revenue trend vs target
    const revenueAgainstTarget = [];
    for (let i = 11; i >= 0; i--) {
      const d = new Date(now.getFullYear(), now.getMonth() - i, 1);
      const m = d.getMonth();
      const y = d.getFullYear();
      const monthWon = pastWonDealsYear
        .filter((deal) => {
          const date = deal.closedAt || deal.closeDate;
          if (!date) return false;
          const dt = new Date(date);
          return dt.getMonth() === m && dt.getFullYear() === y;
        })
        .reduce((sum, deal) => sum + Number(deal.amount), 0);
      revenueAgainstTarget.push({
        month: `${MONTH_NAMES[m]}`,
        fullMonth: `${MONTH_NAMES[m]} ${y}`,
        revenue: monthWon,
        target: Math.max(monthWon, 450000),
      });
    }

    // Reps sales leaderboard
    const leaderboard = repsLeaderboardUsers
      .map((u) => {
        const wonDeals = u.assignedDeals.filter((d) => d.stage === DealStage.CLOSED_WON);
        const wonRev = wonDeals.reduce((sum, d) => sum + Number(d.amount), 0);
        return {
          userId: u.id,
          name: u.name,
          dealsCount: wonDeals.length,
          wonRevenue: wonRev,
        };
      })
      .sort((a, b) => b.wonRevenue - a.wonRevenue);

    const readable = await this.readableModules(ctx);
    const has = (module: string) => readable === null || readable.has(module);
    const access = { deals: has('deals'), leads: has('leads'), tasks: has('tasks'), projects: has('projects') || has('timesheets'), activities: has('activities') };

    const kpis = {
      revenueWon: access.deals ? revenueWon : 0,
      openPipeline: access.deals ? openPipeline : 0,
      weightedPipeline: access.deals ? weightedPipeline : 0,
      winRate: access.deals ? winRate : 0,
      wonCount: access.deals ? wonCount : 0,
      lostCount: access.deals ? lostCount : 0,
      newLeadsCount: access.leads ? newLeadsCount : 0,
      qualifiedLeadsCount: access.leads ? qualifiedLeadsCount : 0,
    };
    const delivery = access.projects ? { activeProjectsCount: activeProjects.length, atRiskProjectsCount, teamHoursThisWeek, billableHoursThisWeek } : { activeProjectsCount: 0, atRiskProjectsCount: 0, teamHoursThisWeek: 0, billableHoursThisWeek: 0 };
    const visibleStages = access.deals ? stageBreakdown : [];

    return {
      period: periodKey,
      periodLabel,
      access,
      kpis,
      kpi: kpis,
      pipelineStages: visibleStages,
      stageBreakdown: visibleStages,
      leadSources: access.leads ? leadSources : [],
      todayTasks: access.tasks ? todayTasks : [],
      attentionDeals: access.deals
        ? attentionDeals.map((d) => ({
            ...d,
            amount: Number(d.amount),
            daysInStage: computeDaysInStage(d.stageChangedAt),
          }))
        : [],
      revenueAgainstTarget: access.deals ? revenueAgainstTarget : [],
      leaderboard: access.deals ? leaderboard : [],
      delivery,
      deliveryMetrics: delivery,
      recentActivities: access.activities ? recentActivities : [],
    };
  }

  /** Returns the modules a member may read, using the permission guard's rules; null means no limit (admins and members who have no role at all). */
  private async readableModules(ctx: RequestTenantContext): Promise<Set<string> | null> {
    if (ctx.role !== UserRole.ORGANIZATION_MEMBER) return null;
    const user = await this.prisma.user.findUnique({ where: { id: ctx.userId }, select: { roleId: true, customRole: { select: { permissions: true } } } });
    if (!user?.roleId && !user?.customRole) return null;
    const permissions = user.customRole?.permissions ?? [];
    return new Set(permissions.filter((p) => p.canRead || p.canCreate || p.canUpdate || p.canDelete || p.canExport).map((p) => p.module));
  }

  // Resolves the start and end timestamp based on query or period parameters.
  private resolveQueryDates(
    queryOrPeriod?: DashboardQuery | string,
    defaultPeriod: string = 'today',
  ): {
    start: Date;
    end: Date;
    periodLabel: string;
    periodKey: string;
  } {
    const now = new Date();
    let period = defaultPeriod;
    let startDate: string | undefined;
    let endDate: string | undefined;

    if (typeof queryOrPeriod === 'string') {
      period = queryOrPeriod;
    } else if (queryOrPeriod) {
      period = queryOrPeriod.period || defaultPeriod;
      startDate = queryOrPeriod.startDate;
      endDate = queryOrPeriod.endDate;
    }

    if (startDate && endDate) {
      const start = new Date(startDate);
      if (!startDate.includes('T')) start.setHours(0, 0, 0, 0);
      const end = new Date(endDate);
      if (!endDate.includes('T')) end.setHours(23, 59, 59, 999);
      const fmt = (d: Date) => d.toLocaleDateString('en-IN', { day: '2-digit', month: 'short', year: 'numeric' });
      return {
        start,
        end,
        periodLabel: `${fmt(start)} – ${fmt(end)}`,
        periodKey: 'custom',
      };
    }

    if (period === 'today') {
      const start = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0, 0);
      const end = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59, 999);
      const fmt = (d: Date) => d.toLocaleDateString('en-IN', { day: '2-digit', month: 'short', year: 'numeric' });
      return {
        start,
        end,
        periodLabel: `Today (${fmt(start)})`,
        periodKey: 'today',
      };
    }

    if (period === 'yesterday') {
      const y = new Date(now.getTime() - 24 * 60 * 60 * 1000);
      const start = new Date(y.getFullYear(), y.getMonth(), y.getDate(), 0, 0, 0, 0);
      const end = new Date(y.getFullYear(), y.getMonth(), y.getDate(), 23, 59, 59, 999);
      const fmt = (d: Date) => d.toLocaleDateString('en-IN', { day: '2-digit', month: 'short', year: 'numeric' });
      return {
        start,
        end,
        periodLabel: `Yesterday (${fmt(start)})`,
        periodKey: 'yesterday',
      };
    }

    if (period === 'week') {
      const start = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
      start.setHours(0, 0, 0, 0);
      const end = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59, 999);
      const fmt = (d: Date) => d.toLocaleDateString('en-IN', { day: '2-digit', month: 'short' });
      return {
        start,
        end,
        periodLabel: `This Week (${fmt(start)} – ${fmt(end)})`,
        periodKey: 'week',
      };
    }

    if (period === 'all') {
      return {
        start: new Date(2000, 0, 1),
        end: new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59, 999),
        periodLabel: 'All Time',
        periodKey: 'all',
      };
    }

    if (period === 'year') {
      const start = new Date(now.getFullYear(), 0, 1);
      const end = new Date(now.getFullYear(), 11, 31, 23, 59, 59, 999);
      return {
        start,
        end,
        periodLabel: `Year ${now.getFullYear()}`,
        periodKey: 'year',
      };
    }

    if (period === 'quarter') {
      const qMonth = Math.floor(now.getMonth() / 3) * 3;
      const start = new Date(now.getFullYear(), qMonth, 1);
      const end = new Date(now.getFullYear(), qMonth + 3, 0, 23, 59, 59, 999);
      const qNum = Math.floor(now.getMonth() / 3) + 1;
      return {
        start,
        end,
        periodLabel: `Q${qNum} ${now.getFullYear()}`,
        periodKey: 'quarter',
      };
    }

    // Default: current month
    const start = new Date(now.getFullYear(), now.getMonth(), 1);
    const end = new Date(now.getFullYear(), now.getMonth() + 1, 0, 23, 59, 59, 999);
    return {
      start,
      end,
      periodLabel: `${MONTH_NAMES[now.getMonth()]} ${now.getFullYear()}`,
      periodKey: 'month',
    };
  }

  // Returns detailed sales, rep performance, and conversion reports.
  async getReports(ctx: RequestTenantContext, queryOrPeriod?: DashboardQuery | string) {
    const { start, end, periodLabel, periodKey } = this.resolveQueryDates(queryOrPeriod, 'month');
    const now = new Date();

    const [allLeads, allDeals, orgUsers, pastWonDeals, openForecastDeals] = await Promise.all([
      this.prisma.lead.findMany({
        where: this.tenant.scopeWhere(ctx),
        select: { id: true, status: true, source: true, createdAt: true, convertedAccountId: true, convertedContactId: true, convertedDealId: true },
      }),
      this.prisma.deal.findMany({
        where: this.tenant.scopeWhere(ctx),
        select: { id: true, stage: true, amount: true, lossReason: true, closedAt: true, closeDate: true, createdAt: true, ownerId: true, owner: { select: { id: true, name: true } } },
      }),
      this.prisma.user.findMany({
        where: this.tenant.scopeWhere(ctx, { status: UserStatus.ACTIVE }),
        select: {
          id: true,
          name: true,
          assignedDeals: {
            where: this.tenant.scopeWhere(ctx),
            select: { stage: true, amount: true, createdAt: true },
          },
        },
      }),
      this.prisma.deal.findMany({
        where: this.tenant.scopeWhere(ctx, {
          stage: DealStage.CLOSED_WON,
        }),
        select: { amount: true, closedAt: true, closeDate: true, createdAt: true },
      }),
      this.prisma.deal.findMany({
        where: this.tenant.scopeWhere(ctx, { stage: { in: [...OPEN_DEAL_STAGES] } }),
        select: { amount: true, stage: true, closeDate: true, createdAt: true },
      }),
    ]);

    const isCustom = Boolean(typeof queryOrPeriod === 'object' && queryOrPeriod?.startDate);
    const periodLeads = allLeads.filter((l) => l.createdAt >= start && l.createdAt <= end);
    const activeLeads = isCustom ? periodLeads : periodLeads.length > 0 ? periodLeads : allLeads;

    const periodDeals = allDeals.filter((d) => {
      const dt = d.closedAt || d.closeDate || d.createdAt;
      return dt && dt >= start && dt <= end;
    });
    const activeDeals = isCustom ? periodDeals : periodDeals.length > 0 ? periodDeals : allDeals;

    const totalLeads = activeLeads.length;
    const qualifiedLeads = activeLeads.filter((l) => l.status === LeadStatus.QUALIFIED || l.status === LeadStatus.CONVERTED).length;
    const proposalStages: DealStage[] = [DealStage.PROPOSAL, DealStage.NEGOTIATION, DealStage.CLOSED_WON];
    const negotiationStages: DealStage[] = [DealStage.NEGOTIATION, DealStage.CLOSED_WON];
    const proposalDeals = activeDeals.filter((d) => proposalStages.includes(d.stage)).length;
    const negotiationDeals = activeDeals.filter((d) => negotiationStages.includes(d.stage)).length;
    const wonDeals = activeDeals.filter((d) => d.stage === DealStage.CLOSED_WON);
    const lostDeals = activeDeals.filter((d) => d.stage === DealStage.CLOSED_LOST);

    const funnel = [
      { step: 'All Leads', count: totalLeads },
      { step: 'Qualified', count: qualifiedLeads },
      { step: 'Proposal Sent', count: proposalDeals },
      { step: 'Negotiation', count: negotiationDeals },
      { step: 'Closed Won', count: wonDeals.length },
    ];

    const revenueByRep = orgUsers
      .map((r) => {
        const won = r.assignedDeals.filter((d) => d.stage === DealStage.CLOSED_WON).reduce((s, d) => s + Number(d.amount), 0);
        const pipeline = r.assignedDeals.filter((d) => OPEN_DEAL_STAGES.includes(d.stage)).reduce((s, d) => s + Number(d.amount), 0);
        return {
          repId: r.id,
          name: r.name,
          wonRevenue: won,
          openPipeline: pipeline,
        };
      })
      .filter((r) => r.wonRevenue > 0 || r.openPipeline > 0 || orgUsers.length <= 4);

    const lossReasonsMap = new Map<string, number>();
    for (const d of lostDeals) {
      const reason = d.lossReason || NOT_SPECIFIED;
      lossReasonsMap.set(reason, (lossReasonsMap.get(reason) || 0) + 1);
    }
    const lossReasons = Array.from(lossReasonsMap.entries()).map(([reason, count]) => ({ reason, count }));

    // Lead source quality from real database leads
    const distinctSources = Array.from(new Set(activeLeads.map((l) => l.source || NOT_SPECIFIED)));
    const allSources = Array.from(new Set([...LEAD_SOURCES, ...distinctSources]));

    const leadSourceQuality = allSources
      .map((src) => {
        const srcLeads = activeLeads.filter((l) => (l.source || NOT_SPECIFIED) === src);
        const qualified = srcLeads.filter((l) => l.status === LeadStatus.QUALIFIED || l.status === LeadStatus.CONVERTED).length;
        const converted = srcLeads.filter((l) => l.status === LeadStatus.CONVERTED).length;
        const rate = srcLeads.length > 0 ? Math.round((qualified / srcLeads.length) * 100) : 0;
        return {
          source: src,
          total: srcLeads.length,
          qualified,
          converted,
          conversionRate: rate,
        };
      })
      .sort((a, b) => b.total - a.total);

    // 12-month bookings for bar chart
    const monthlyBookings = [];
    for (let i = 11; i >= 0; i--) {
      const d = new Date(now.getFullYear(), now.getMonth() - i, 1);
      const m = d.getMonth();
      const y = d.getFullYear();
      const total = pastWonDeals
        .filter((deal) => {
          const date = deal.closedAt || deal.closeDate || deal.createdAt;
          if (!date) return false;
          const dt = new Date(date);
          return dt.getMonth() === m && dt.getFullYear() === y;
        })
        .reduce((sum, deal) => sum + Number(deal.amount), 0);
      monthlyBookings.push({
        month: `${MONTH_NAMES[m]}`,
        year: y,
        bookings: total,
      });
    }

    // 3-month forecast table from real database deals
    const forecast = [0, 1, 2].map((offset) => {
      const targetDate = new Date(now.getFullYear(), now.getMonth() + offset, 1);
      const targetMonth = targetDate.getMonth();
      const targetYear = targetDate.getFullYear();
      const ds = openForecastDeals.filter((deal) => {
        const date = deal.closeDate || deal.createdAt;
        if (!date) return false;
        const cd = new Date(date);
        return cd.getMonth() === targetMonth && cd.getFullYear() === targetYear;
      });
      const commit = ds.filter((d) => d.stage === DealStage.NEGOTIATION).reduce((s, d) => s + Number(d.amount), 0);
      const bestCase = ds.filter((d) => d.stage === DealStage.PROPOSAL || d.stage === DealStage.NEGOTIATION).reduce((s, d) => s + Number(d.amount), 0);
      const pipe = ds.reduce((s, d) => s + Number(d.amount), 0);
      const weighted = ds.reduce((s, d) => s + computeWeightedAmount(Number(d.amount), d.stage), 0);
      return {
        month: targetDate.toLocaleDateString('en-US', { month: 'long', year: 'numeric' }),
        dealsCount: ds.length,
        commit,
        bestCase,
        pipeline: pipe,
        weighted,
      };
    });

    const wonAmount = wonDeals.reduce((s, d) => s + Number(d.amount), 0);
    const lostAmount = lostDeals.reduce((s, d) => s + Number(d.amount), 0);
    const winRate = wonDeals.length + lostDeals.length > 0 ? Math.round((wonDeals.length / (wonDeals.length + lostDeals.length)) * 100) : 0;
    const openPipeline = activeDeals.filter((d) => OPEN_DEAL_STAGES.includes(d.stage)).reduce((s, d) => s + Number(d.amount), 0);

    return {
      period: periodKey,
      periodLabel,
      dateRange: {
        start: start.toISOString(),
        end: end.toISOString(),
      },
      summary: {
        wonRevenue: wonAmount,
        openPipeline,
        winRate,
        totalLeads,
        qualifiedLeads,
        wonDealsCount: wonDeals.length,
        lostDealsCount: lostDeals.length,
      },
      funnel,
      revenueByRep,
      monthlyBookings,
      forecast,
      winLoss: {
        wonCount: wonDeals.length,
        lostCount: lostDeals.length,
        wonAmount,
        lostAmount,
        winRate,
        lossReasons,
      },
      leadSourceQuality,
    };
  }

  // Generates and streams standard sales report as a formatted PDF.
  async exportReportsPdf(ctx: RequestTenantContext, queryOrPeriod?: DashboardQuery | string): Promise<{ buffer: Buffer; filename: string }> {
    const reports = await this.getReports(ctx, queryOrPeriod);
    const tenantId = ctx.tenantId;
    const org = tenantId
      ? await this.prisma.organization.findUnique({
          where: { id: tenantId },
          select: { name: true, legalName: true, city: true },
        })
      : null;
    const orgName = org?.legalName || org?.name || 'TechCMantix CRM';

    const doc = new PDFDocument({ size: 'A4', margin: 40, bufferPages: true });
    const buffers: Buffer[] = [];
    doc.on('data', (chunk) => buffers.push(chunk));

    const formatINR = (val: number | string) => `Rs. ${Number(val || 0).toLocaleString('en-IN', { maximumFractionDigits: 0 })}`;
    const formatDate = (d: Date | string) => new Date(d).toLocaleDateString('en-IN', { day: '2-digit', month: 'short', year: 'numeric' });
    const now = new Date();

    // Top Header Banner
    doc.save();
    doc.rect(40, 40, 515, 60).fill('#0f172a');
    doc.fillColor('#ffffff').fontSize(15).font('Helvetica-Bold').text(orgName.toUpperCase(), 55, 52);
    doc.fontSize(8.5).font('Helvetica').fillColor('#94a3b8').text('SALES PERFORMANCE & ANALYTICS REPORT', 55, 72);

    doc.fontSize(10).font('Helvetica-Bold').fillColor('#f59e0b').text(`PERIOD: ${reports.periodLabel.toUpperCase()}`, 300, 52, { align: 'right', width: 240 });
    doc
      .fontSize(8)
      .font('Helvetica')
      .fillColor('#cbd5e1')
      .text(`Generated: ${formatDate(now)}`, 300, 72, { align: 'right', width: 240 });
    doc.restore();

    let y = 112;

    const checkPageBreak = (neededHeight: number) => {
      if (y + neededHeight > 770) {
        doc.addPage({ size: 'A4', margin: 40 });
        y = 40;
        doc.save();
        doc.rect(40, y, 515, 24).fill('#0f172a');
        doc
          .fillColor('#ffffff')
          .fontSize(9)
          .font('Helvetica-Bold')
          .text(`${orgName.toUpperCase()} — SALES REPORT (${reports.periodLabel.toUpperCase()})`, 50, y + 7);
        doc.restore();
        y += 34;
      }
    };

    // Executive KPI Summary Cards
    const wonCount = reports.winLoss.wonCount;
    const lostCount = reports.winLoss.lostCount;
    const wonAmount = reports.winLoss.wonAmount;
    const winRate = reports.winLoss.winRate;
    const totalLeads = reports.funnel[0]?.count || 0;
    const qualifiedLeads = reports.funnel[1]?.count || 0;

    const cards = [
      { label: 'TOTAL LEADS', value: String(totalLeads), sub: `${qualifiedLeads} Qualified` },
      { label: 'WON REVENUE', value: formatINR(wonAmount), sub: `${wonCount} Deals Won` },
      { label: 'WIN RATE', value: `${winRate}%`, sub: `${wonCount} Won / ${lostCount} Lost` },
      { label: 'OPEN PIPELINE', value: formatINR(reports.revenueByRep.reduce((acc, r) => acc + r.openPipeline, 0)), sub: `${reports.revenueByRep.length} Sales Reps` },
    ];

    const cardWidth = 122;
    const cardGap = 9;
    cards.forEach((card, idx) => {
      const cardX = 40 + idx * (cardWidth + cardGap);
      doc.save();
      doc.roundedRect(cardX, y, cardWidth, 48, 4).fillAndStroke('#f8fafc', '#e2e8f0');
      doc
        .fillColor('#64748b')
        .fontSize(7)
        .font('Helvetica-Bold')
        .text(card.label, cardX + 8, y + 8);
      doc
        .fillColor('#0f172a')
        .fontSize(11)
        .font('Helvetica-Bold')
        .text(card.value, cardX + 8, y + 20, { width: cardWidth - 16, ellipsis: true });
      doc
        .fillColor('#94a3b8')
        .fontSize(6.5)
        .font('Helvetica')
        .text(card.sub, cardX + 8, y + 35);
      doc.restore();
    });

    y += 62;

    const renderSectionTitle = (title: string) => {
      checkPageBreak(35);
      doc.save();
      doc.fillColor('#0f172a').fontSize(10).font('Helvetica-Bold').text(title, 40, y);
      doc.rect(40, y + 14, 515, 1).fill('#e2e8f0');
      doc.restore();
      y += 22;
    };

    const drawTableHeader = (cols: { label: string; width: number; align: string }[]) => {
      checkPageBreak(25);
      doc.save();
      doc.rect(40, y, 515, 18).fill('#f1f5f9');
      doc.strokeColor('#cbd5e1').lineWidth(0.5).rect(40, y, 515, 18).stroke();
      let curX = 40;
      cols.forEach((col) => {
        doc
          .fillColor('#334155')
          .fontSize(7.5)
          .font('Helvetica-Bold')
          .text(col.label, curX + 4, y + 5, { width: col.width - 8, align: col.align as any });
        curX += col.width;
      });
      doc.restore();
      y += 18;
    };

    // 1. Sales Funnel
    renderSectionTitle('1. SALES FUNNEL PROGRESSION');
    const funnelCols = [
      { label: 'FUNNEL STEP', width: 215, align: 'left' },
      { label: 'COUNT', width: 150, align: 'right' },
      { label: 'CONVERSION BENCHMARK', width: 150, align: 'right' },
    ];
    drawTableHeader(funnelCols);

    reports.funnel.forEach((f, idx) => {
      checkPageBreak(18);
      const isAlt = idx % 2 === 1;
      if (isAlt) {
        doc.save();
        doc.rect(40, y, 515, 18).fill('#f8fafc');
        doc.restore();
      }
      const bench = idx === 0 ? 'Baseline (100%)' : `${Math.round((f.count / Math.max(1, totalLeads)) * 100)}% of Leads`;
      doc.save();
      doc
        .fillColor('#0f172a')
        .fontSize(8)
        .font('Helvetica-Bold')
        .text(f.step, 44, y + 5, { width: 207 });
      doc
        .fillColor('#334155')
        .fontSize(8)
        .font('Helvetica')
        .text(String(f.count), 255, y + 5, { width: 142, align: 'right' });
      doc
        .fillColor('#64748b')
        .fontSize(7.5)
        .font('Helvetica')
        .text(bench, 405, y + 5, { width: 142, align: 'right' });
      doc.rect(40, y + 18, 515, 0.5).fill('#f1f5f9');
      doc.restore();
      y += 18;
    });

    y += 14;

    // 2. Revenue by Sales Rep
    renderSectionTitle('2. REVENUE & PIPELINE BY SALES REPRESENTATIVE');
    const repCols = [
      { label: 'REPRESENTATIVE', width: 215, align: 'left' },
      { label: 'WON REVENUE', width: 150, align: 'right' },
      { label: 'OPEN PIPELINE', width: 150, align: 'right' },
    ];
    drawTableHeader(repCols);

    if (reports.revenueByRep.length === 0) {
      checkPageBreak(20);
      doc.save();
      doc
        .fillColor('#94a3b8')
        .fontSize(8)
        .font('Helvetica')
        .text('No representative activity recorded for this period.', 44, y + 5);
      doc.restore();
      y += 20;
    } else {
      let totWon = 0;
      let totPipe = 0;
      reports.revenueByRep.forEach((r, idx) => {
        totWon += r.wonRevenue;
        totPipe += r.openPipeline;
        checkPageBreak(18);
        const isAlt = idx % 2 === 1;
        if (isAlt) {
          doc.save();
          doc.rect(40, y, 515, 18).fill('#f8fafc');
          doc.restore();
        }
        doc.save();
        doc
          .fillColor('#0f172a')
          .fontSize(8)
          .font('Helvetica')
          .text(r.name, 44, y + 5, { width: 207 });
        doc
          .fillColor('#059669')
          .fontSize(8)
          .font('Helvetica-Bold')
          .text(formatINR(r.wonRevenue), 255, y + 5, { width: 142, align: 'right' });
        doc
          .fillColor('#2563eb')
          .fontSize(8)
          .font('Helvetica')
          .text(formatINR(r.openPipeline), 405, y + 5, { width: 142, align: 'right' });
        doc.rect(40, y + 18, 515, 0.5).fill('#f1f5f9');
        doc.restore();
        y += 18;
      });

      // Total Row
      checkPageBreak(20);
      doc.save();
      doc.rect(40, y, 515, 20).fill('#f1f5f9');
      doc
        .fillColor('#0f172a')
        .fontSize(8)
        .font('Helvetica-Bold')
        .text('TOTAL', 44, y + 6);
      doc
        .fillColor('#059669')
        .fontSize(8)
        .font('Helvetica-Bold')
        .text(formatINR(totWon), 255, y + 6, { width: 142, align: 'right' });
      doc
        .fillColor('#2563eb')
        .fontSize(8)
        .font('Helvetica-Bold')
        .text(formatINR(totPipe), 405, y + 6, { width: 142, align: 'right' });
      doc.restore();
      y += 20;
    }

    y += 14;

    // 3. Lead Source Quality
    renderSectionTitle('3. LEAD SOURCE PERFORMANCE');
    const sourceCols = [
      { label: 'SOURCE CHANNEL', width: 175, align: 'left' },
      { label: 'TOTAL LEADS', width: 85, align: 'right' },
      { label: 'QUALIFIED', width: 85, align: 'right' },
      { label: 'CONVERTED', width: 85, align: 'right' },
      { label: 'WIN RATE', width: 85, align: 'right' },
    ];
    drawTableHeader(sourceCols);

    const activeSources = reports.leadSourceQuality.filter((sq) => sq.total > 0);
    if (activeSources.length === 0) {
      checkPageBreak(20);
      doc.save();
      doc
        .fillColor('#94a3b8')
        .fontSize(8)
        .font('Helvetica')
        .text('No lead source records found for this period.', 44, y + 5);
      doc.restore();
      y += 20;
    } else {
      activeSources.forEach((sq, idx) => {
        checkPageBreak(18);
        const isAlt = idx % 2 === 1;
        if (isAlt) {
          doc.save();
          doc.rect(40, y, 515, 18).fill('#f8fafc');
          doc.restore();
        }
        doc.save();
        doc
          .fillColor('#0f172a')
          .fontSize(8)
          .font('Helvetica')
          .text(sq.source, 44, y + 5, { width: 167 });
        doc
          .fillColor('#334155')
          .fontSize(8)
          .font('Helvetica')
          .text(String(sq.total), 215, y + 5, { width: 77, align: 'right' });
        doc
          .fillColor('#334155')
          .fontSize(8)
          .font('Helvetica')
          .text(String(sq.qualified), 300, y + 5, { width: 77, align: 'right' });
        doc
          .fillColor('#059669')
          .fontSize(8)
          .font('Helvetica')
          .text(String(sq.converted), 385, y + 5, { width: 77, align: 'right' });
        doc
          .fillColor('#2563eb')
          .fontSize(8)
          .font('Helvetica-Bold')
          .text(`${sq.conversionRate}%`, 470, y + 5, { width: 77, align: 'right' });
        doc.rect(40, y + 18, 515, 0.5).fill('#f1f5f9');
        doc.restore();
        y += 18;
      });
    }

    y += 14;

    // 4. Win / Loss Breakdown
    renderSectionTitle('4. WIN / LOSS ANALYSIS & LOSS REASONS');
    checkPageBreak(24);
    doc.save();
    doc
      .fillColor('#475569')
      .fontSize(8)
      .font('Helvetica')
      .text(`Summary: ${wonCount} Won deals (${formatINR(wonAmount)})   |   ${lostCount} Lost deals (${formatINR(reports.winLoss.lostAmount)})   |   Overall Win Rate: ${winRate}%`, 40, y);
    doc.restore();
    y += 16;

    const lossCols = [
      { label: 'LOSS REASON', width: 365, align: 'left' },
      { label: 'COUNT', width: 150, align: 'right' },
    ];
    drawTableHeader(lossCols);

    if (reports.winLoss.lossReasons.length === 0) {
      checkPageBreak(20);
      doc.save();
      doc
        .fillColor('#94a3b8')
        .fontSize(8)
        .font('Helvetica')
        .text('No loss reasons recorded.', 44, y + 5);
      doc.restore();
      y += 20;
    } else {
      reports.winLoss.lossReasons.forEach((lr, idx) => {
        checkPageBreak(18);
        const isAlt = idx % 2 === 1;
        if (isAlt) {
          doc.save();
          doc.rect(40, y, 515, 18).fill('#f8fafc');
          doc.restore();
        }
        doc.save();
        doc
          .fillColor('#0f172a')
          .fontSize(8)
          .font('Helvetica')
          .text(lr.reason, 44, y + 5, { width: 357 });
        doc
          .fillColor('#dc2626')
          .fontSize(8)
          .font('Helvetica-Bold')
          .text(String(lr.count), 405, y + 5, { width: 142, align: 'right' });
        doc.rect(40, y + 18, 515, 0.5).fill('#f1f5f9');
        doc.restore();
        y += 18;
      });
    }

    // Footers across all pages
    const range = doc.bufferedPageRange();
    for (let i = range.start; i < range.start + range.count; i++) {
      doc.switchToPage(i);
      doc.save();
      doc.page.margins.bottom = 0;
      doc.rect(40, 770, 515, 0.5).fill('#cbd5e1');
      doc.fillColor('#94a3b8').fontSize(7.5).font('Helvetica');
      doc.text('TechCMantix CRM  |  Sales Performance & Analytics Report (Confidential)', 40, 778, { width: 340, align: 'left', lineBreak: false });
      doc.text(`Page ${i + 1} of ${range.count}`, 380, 778, { width: 175, align: 'right', lineBreak: false });
      doc.restore();
    }

    doc.end();

    return new Promise((resolve, reject) => {
      doc.on('end', () => {
        resolve({
          buffer: Buffer.concat(buffers),
          filename: `sales-report-${reports.period || 'custom'}-${new Date().toISOString().slice(0, 10)}.pdf`,
        });
      });
      doc.on('error', reject);
    });
  }

  // Generates and streams custom builder report as a formatted PDF.
  async exportCustomReportPdf(ctx: RequestTenantContext, dto: ExportCustomReportDto): Promise<{ buffer: Buffer; filename: string }> {
    const tenantId = ctx.tenantId;
    const org = tenantId
      ? await this.prisma.organization.findUnique({
          where: { id: tenantId },
          select: { name: true, legalName: true },
        })
      : null;
    const orgName = org?.legalName || org?.name || 'TechCMantix CRM';

    const doc = new PDFDocument({ size: 'A4', margin: 40, bufferPages: true });
    const buffers: Buffer[] = [];
    doc.on('data', (chunk) => buffers.push(chunk));

    const isAmount = /amount|revenue|value/i.test(dto.measure);
    const formatVal = (v: number) => (isAmount ? `Rs. ${Number(v || 0).toLocaleString('en-IN', { maximumFractionDigits: 0 })}` : Number(v || 0).toLocaleString('en-IN'));
    const now = new Date();
    const dateStr = now.toLocaleDateString('en-IN', { day: '2-digit', month: 'short', year: 'numeric' });

    // Header banner
    doc.save();
    doc.rect(40, 40, 515, 60).fill('#0f172a');
    doc.fillColor('#ffffff').fontSize(14).font('Helvetica-Bold').text(orgName.toUpperCase(), 55, 52);
    doc.fontSize(8.5).font('Helvetica').fillColor('#94a3b8').text('CUSTOM ANALYTICS REPORT', 55, 72);

    doc.fontSize(11).font('Helvetica-Bold').fillColor('#38bdf8').text(dto.name.toUpperCase(), 300, 52, { align: 'right', width: 240, ellipsis: true });
    doc.fontSize(8).font('Helvetica').fillColor('#cbd5e1').text(`Generated: ${dateStr}`, 300, 72, { align: 'right', width: 240 });
    doc.restore();

    let y = 115;

    // Report Metadata Info Box
    doc.save();
    doc.roundedRect(40, y, 515, 42, 4).fillAndStroke('#f8fafc', '#e2e8f0');
    const metaItems = [
      { label: 'OBJECT', val: dto.object },
      { label: 'GROUPED BY', val: dto.group },
      { label: 'MEASURE', val: dto.measure },
      { label: 'CHART FORMAT', val: dto.chart || 'Bar' },
    ];
    metaItems.forEach((m, idx) => {
      const mx = 55 + idx * 125;
      doc
        .fillColor('#64748b')
        .fontSize(7)
        .font('Helvetica-Bold')
        .text(m.label, mx, y + 9);
      doc
        .fillColor('#0f172a')
        .fontSize(9)
        .font('Helvetica-Bold')
        .text(m.val, mx, y + 22);
    });
    doc.restore();

    y += 56;

    // Table
    const cols = [
      { label: '#', width: 35, align: 'center' },
      { label: dto.group.toUpperCase(), width: 260, align: 'left' },
      { label: dto.measure.toUpperCase(), width: 140, align: 'right' },
      { label: 'SHARE', width: 80, align: 'right' },
    ];

    doc.save();
    doc.rect(40, y, 515, 20).fill('#f1f5f9');
    doc.strokeColor('#cbd5e1').lineWidth(0.5).rect(40, y, 515, 20).stroke();
    let cx = 40;
    cols.forEach((col) => {
      doc
        .fillColor('#334155')
        .fontSize(7.5)
        .font('Helvetica-Bold')
        .text(col.label, cx + 4, y + 6, { width: col.width - 8, align: col.align as any });
      cx += col.width;
    });
    doc.restore();
    y += 20;

    const rows = dto.rows || [];
    const totalVal = rows.reduce((s, r) => s + (Number(r[1]) || 0), 0);

    if (rows.length === 0) {
      doc.save();
      doc
        .fillColor('#94a3b8')
        .fontSize(8.5)
        .font('Helvetica')
        .text('No data for this report in the selected period.', 44, y + 10);
      doc.restore();
      y += 30;
    } else {
      rows.forEach((r, idx) => {
        if (y + 20 > 770) {
          doc.addPage({ size: 'A4', margin: 40 });
          y = 40;
        }
        const isAlt = idx % 2 === 1;
        if (isAlt) {
          doc.save();
          doc.rect(40, y, 515, 20).fill('#f8fafc');
          doc.restore();
        }
        const val = Number(r[1]) || 0;
        const pct = totalVal > 0 ? `${Math.round((val / totalVal) * 100)}%` : '0%';

        doc.save();
        doc
          .fillColor('#64748b')
          .fontSize(8)
          .font('Helvetica')
          .text(String(idx + 1), 44, y + 6, { width: 27, align: 'center' });
        doc
          .fillColor('#0f172a')
          .fontSize(8)
          .font('Helvetica-Bold')
          .text(String(r[0] || 'Unknown'), 79, y + 6, { width: 252 });
        doc
          .fillColor('#2563eb')
          .fontSize(8)
          .font('Helvetica-Bold')
          .text(formatVal(val), 339, y + 6, { width: 132, align: 'right' });
        doc
          .fillColor('#64748b')
          .fontSize(8)
          .font('Helvetica')
          .text(pct, 479, y + 6, { width: 72, align: 'right' });
        doc.rect(40, y + 20, 515, 0.5).fill('#f1f5f9');
        doc.restore();
        y += 20;
      });

      // Total row
      doc.save();
      doc.rect(40, y, 515, 22).fill('#f1f5f9');
      doc
        .fillColor('#0f172a')
        .fontSize(8.5)
        .font('Helvetica-Bold')
        .text('TOTAL', 79, y + 6);
      doc
        .fillColor('#2563eb')
        .fontSize(8.5)
        .font('Helvetica-Bold')
        .text(formatVal(totalVal), 339, y + 6, { width: 132, align: 'right' });
      doc
        .fillColor('#0f172a')
        .fontSize(8.5)
        .font('Helvetica-Bold')
        .text('100%', 479, y + 6, { width: 72, align: 'right' });
      doc.restore();
      y += 22;
    }

    // Footers
    const range = doc.bufferedPageRange();
    for (let i = range.start; i < range.start + range.count; i++) {
      doc.switchToPage(i);
      doc.save();
      doc.page.margins.bottom = 0;
      doc.rect(40, 770, 515, 0.5).fill('#cbd5e1');
      doc.fillColor('#94a3b8').fontSize(7.5).font('Helvetica');
      doc.text(`TechCMantix CRM  |  Custom Report: ${dto.name}`, 40, 778, { width: 340, align: 'left', lineBreak: false });
      doc.text(`Page ${i + 1} of ${range.count}`, 380, 778, { width: 175, align: 'right', lineBreak: false });
      doc.restore();
    }

    doc.end();

    const slug = dto.name.toLowerCase().replace(/[^a-z0-9]+/g, '-');
    return new Promise((resolve, reject) => {
      doc.on('end', () => {
        resolve({
          buffer: Buffer.concat(buffers),
          filename: `custom-report-${slug}-${new Date().toISOString().slice(0, 10)}.pdf`,
        });
      });
      doc.on('error', reject);
    });
  }

  // Returns all saved custom reports for tenant, seeding defaults if empty.
  async getCustomReports(ctx: RequestTenantContext) {
    const tenantId = this.tenant.getRequiredTenantId(ctx);
    const existing = await this.prisma.customReport.findMany({
      where: { tenantId },
      orderBy: { createdAt: 'desc' },
    });
    if (existing.length > 0) {
      return existing;
    }

    // If the tenant already initialized reports and subsequently deleted them all, do not recreate defaults
    const initialized = await this.prisma.auditEvent.findFirst({
      where: { tenantId, action: 'CUSTOM_REPORTS_INITIALIZED' },
    });
    if (initialized) {
      return [];
    }

    const defaults = [
      { name: 'Deals by Sales Owner', object: 'Deals', group: 'Owner', measure: 'Won amount', chart: 'Bar' },
      { name: 'Leads by Acquisition Source', object: 'Leads', group: 'Source', measure: 'Count', chart: 'Donut' },
      { name: 'Deal Loss Reasons Analysis', object: 'Deals', group: 'Loss reason', measure: 'Count', chart: 'Donut' },
      { name: 'Funnel Stage Velocity', object: 'Deals', group: 'Funnel step', measure: 'Count', chart: 'Table' },
    ];
    const created = await Promise.all(
      defaults.map((d) =>
        this.prisma.customReport.create({
          data: {
            ...d,
            tenantId,
            createdById: ctx.userId || null,
          },
        }),
      ),
    );

    await this.prisma.auditEvent.create({
      data: {
        tenantId,
        action: 'CUSTOM_REPORTS_INITIALIZED',
        entityType: 'CustomReport',
        entityId: tenantId,
        summary: 'Custom reports starter templates initialized',
        userId: ctx.userId || null,
      },
    }).catch(() => {});

    return created;
  }

  // Saves a new custom report.
  async createCustomReport(ctx: RequestTenantContext, dto: SaveCustomReportDto) {
    const tenantId = this.tenant.getRequiredTenantId(ctx);
    const shapeError = validateReportShape(dto.object, dto.group, dto.measure);
    if (shapeError) throw new BadRequestException(shapeError);
    return this.prisma.customReport.create({
      data: {
        name: dto.name,
        object: dto.object,
        group: dto.group,
        measure: dto.measure,
        chart: dto.chart,
        tenantId,
        createdById: ctx.userId || null,
      },
    });
  }

  // Updates an existing custom report.
  async updateCustomReport(ctx: RequestTenantContext, id: string, dto: UpdateCustomReportDto) {
    const tenantId = this.tenant.getRequiredTenantId(ctx);
    const report = await this.prisma.customReport.findFirst({
      where: { id, tenantId },
    });
    if (!report) {
      throw new NotFoundException(`Custom report with id "${id}" not found`);
    }
    const shapeError = validateReportShape(dto.object ?? report.object, dto.group ?? report.group, dto.measure ?? report.measure);
    if (shapeError) throw new BadRequestException(shapeError);
    return this.prisma.customReport.update({
      where: { id },
      data: {
        ...(dto.name ? { name: dto.name } : {}),
        ...(dto.object ? { object: dto.object } : {}),
        ...(dto.group ? { group: dto.group } : {}),
        ...(dto.measure ? { measure: dto.measure } : {}),
        ...(dto.chart ? { chart: dto.chart } : {}),
      },
    });
  }

  // Deletes a custom report.
  async deleteCustomReport(ctx: RequestTenantContext, id: string) {
    const tenantId = this.tenant.getRequiredTenantId(ctx);
    const report = await this.prisma.customReport.findFirst({
      where: { id, tenantId },
    });
    if (!report) {
      throw new NotFoundException(`Custom report with id "${id}" not found`);
    }
    await this.prisma.customReport.delete({
      where: { id },
    });
    return { success: true, message: 'Custom report deleted successfully' };
  }
}
