import { BedStatus, InvoiceType } from '@prisma/client';
import { db } from '../../lib/prisma';
import { monthRange } from '../../lib/period';
import { getTenantIdOrThrow } from '../../lib/tenantContext';
import { tenantHasFeature } from '../../middleware/requireFeature';

/** The last `count` periods ending with `endPeriod` (inclusive), oldest first. */
export function periodsEndingAt(endPeriod: string, count: number): string[] {
  const [y, m] = endPeriod.split('-').map(Number);
  const out: string[] = [];
  for (let i = count - 1; i >= 0; i--) {
    const d = new Date(Date.UTC(y, m - 1 - i, 1));
    out.push(`${d.getUTCFullYear()}-${String(d.getUTCMonth() + 1).padStart(2, '0')}`);
  }
  return out;
}

export interface AnalyticsOptions {
  endPeriod: string;
  months: number;
  propertyId?: string;
}

/**
 * All four dashboards in one round-trip.
 *
 * Revenue, dues and mess series are computed from real historical rows
 * (payments, invoices, attendance). The OCCUPANCY series is necessarily
 * *derived*: we don't snapshot bed state over time, so each month counts the
 * students who had been onboarded onto a bed by that month's end, measured
 * against today's bed count. It's an honest approximation of the trend, not a
 * historical record — a nightly snapshot table would be the exact solution.
 */
export async function getAnalytics({ endPeriod, months, propertyId }: AnalyticsOptions) {
  const periods = periodsEndingAt(endPeriod, months);
  const first = monthRange(periods[0]).start;
  const last = monthRange(periods[periods.length - 1]).end;
  const studentScope = propertyId ? { propertyId } : {};
  // Where no money is shown (Enterprise), revenue and dues read zero: the rows are never loaded.
  const tenantId = getTenantIdOrThrow();
  const [billed, booked] = await Promise.all([tenantHasFeature(tenantId, 'billing'), tenantHasFeature(tenantId, 'expenses')]);

  const [beds, students, payments, invoices, attendance, expenses] = await Promise.all([
    db.bed.findMany({
      where: { archivedAt: null, room: { floor: { not: null }, ...(propertyId ? { propertyId } : {}) } },
      select: { status: true },
    }),
    db.studentProfile.findMany({ where: studentScope, select: { createdAt: true, bedId: true } }),
    billed
      ? db.payment.findMany({
          where: { paidAt: { gte: first, lte: last }, ...(propertyId ? { invoice: { student: { propertyId } } } : {}) },
          select: { amount: true, paidAt: true, invoice: { select: { type: true } } },
        })
      : [],
    billed
      ? db.invoice.findMany({
          where: {
            periodMonth: { in: periods },
            ...(propertyId ? { student: { propertyId } } : {}),
          },
          select: { amount: true, periodMonth: true, type: true, payments: { where: { status: 'CLEARED' }, select: { amount: true } } },
        })
      : [],
    db.messAttendance.findMany({
      where: { date: { gte: first, lte: last }, ...(propertyId ? { student: { propertyId } } : {}) },
      select: { date: true, present: true },
    }),
    booked
      ? db.expense.findMany({
          where: { date: { gte: first, lte: last }, ...(propertyId ? { propertyId } : {}) },
          select: { date: true, amount: true },
        })
      : [],
  ]);

  const totalBeds = beds.length;
  const currentOccupied = beds.filter((b) => b.status === BedStatus.OCCUPIED).length;

  const series = periods.map((period) => {
    const { start, end } = monthRange(period);

    // — Occupancy (derived, see note above)
    const onboardedByThen = students.filter((s) => s.bedId && s.createdAt <= end).length;
    const occupied = Math.min(onboardedByThen, totalBeds);

    // — Revenue vs expenses (real rows)
    const monthPayments = payments.filter((p) => p.paidAt >= start && p.paidAt <= end);
    const rent = monthPayments.filter((p) => p.invoice.type === InvoiceType.RENT).reduce((n, p) => n + p.amount, 0);
    const mess = monthPayments.filter((p) => p.invoice.type === InvoiceType.MESS).reduce((n, p) => n + p.amount, 0);
    const spend = expenses.filter((e) => e.date >= start && e.date <= end).reduce((n, e) => n + e.amount, 0);

    // — Dues / collection (real rows)
    const monthInvoices = invoices.filter((i) => i.periodMonth === period);
    const invoiced = monthInvoices.reduce((n, i) => n + i.amount, 0);
    const collected = monthInvoices.reduce((n, i) => n + i.payments.reduce((m, p) => m + p.amount, 0), 0);

    // — Mess attendance (real rows): opt-outs recorded that month
    const monthAttendance = attendance.filter((a) => a.date >= start && a.date <= end);
    const optedOut = monthAttendance.filter((a) => !a.present).length;
    const confirmed = monthAttendance.filter((a) => a.present).length;

    return {
      period,
      occupancy: { occupied, totalBeds, rate: totalBeds ? Math.round((occupied / totalBeds) * 100) : 0 },
      revenue: { rent, mess, total: rent + mess, expenses: spend, net: rent + mess - spend },
      dues: {
        invoiced,
        collected,
        outstanding: Math.max(0, invoiced - collected),
        collectionRate: invoiced ? Math.round((collected / invoiced) * 100) : 0,
      },
      mess: { confirmed, optedOut },
    };
  });

  const totals = series.reduce(
    (acc, s) => ({
      revenue: acc.revenue + s.revenue.total,
      expenses: acc.expenses + s.revenue.expenses,
      invoiced: acc.invoiced + s.dues.invoiced,
      collected: acc.collected + s.dues.collected,
    }),
    { revenue: 0, expenses: 0, invoiced: 0, collected: 0 },
  );

  return {
    periods,
    series,
    summary: {
      totalBeds,
      currentOccupancyRate: totalBeds ? Math.round((currentOccupied / totalBeds) * 100) : 0,
      revenue: totals.revenue,
      expenses: totals.expenses,
      net: totals.revenue - totals.expenses,
      outstanding: Math.max(0, totals.invoiced - totals.collected),
      collectionRate: totals.invoiced ? Math.round((totals.collected / totals.invoiced) * 100) : 0,
    },
    /** Flags which series are exact vs derived, so the UI can be honest too. */
    notes: { occupancyIsDerived: true },
  };
}
