import { SubscriptionStatus, TenantKind, TenantStatus } from '@prisma/client';
import { prismaUnscoped } from '../../lib/prisma';
import { outstanding } from '../subscriptions/subscriptions.service';

/**
 * The super admin's overview: how the business is doing and what needs a
 * hand today. Platform-level like the rest of the super-admin surface, so it
 * reads through the unscoped client, and everything is aggregated in a few
 * grouped queries rather than one per hostel.
 *
 * Revenue figures are whole rupees. "This month" and the 12-month trend are
 * calendar months in India time.
 */

const IST = 5.5 * 3_600_000;
const DAY = 86_400_000;

/** Start of the calendar month (India) `back` months before now, as a UTC instant. */
function monthStart(now: Date, back = 0): Date {
  const local = new Date(now.getTime() + IST);
  return new Date(Date.UTC(local.getUTCFullYear(), local.getUTCMonth() - back, 1) - IST);
}
const monthKey = (d: Date) => new Date(d.getTime() + IST).toISOString().slice(0, 7);

const pct = (part: number, whole: number) => (whole > 0 ? Math.round((part / whole) * 1000) / 10 : null);
/** Change from `prev` to `cur` as a percentage, or null when there is no base. */
const change = (cur: number, prev: number) => (prev > 0 ? Math.round(((cur - prev) / prev) * 1000) / 10 : null);

export async function platformDashboard(now = new Date()) {
  const thisMonth = monthStart(now);
  const lastMonth = monthStart(now, 1);
  const yearAgo = monthStart(now, 11);
  const local = new Date(now.getTime() + IST);
  const yearStart = new Date(Date.UTC(local.getUTCFullYear(), 0, 1) - IST);
  const today = new Date(Date.UTC(local.getUTCFullYear(), local.getUTCMonth(), local.getUTCDate(), 12));

  const [tenants, propsBy, bedsBy, residentsBy, housedBy, rentBy, rentRecentBy, invoices, payments, open, lastIssued] = await Promise.all([
    prismaUnscoped.tenant.findMany({
      select: {
        id: true,
        name: true,
        kind: true,
        status: true,
        createdAt: true,
        suspendedAt: true,
        suspendedReason: true,
        planRef: { select: { id: true, name: true, monthlyPrice: true, maxProperties: true, maxBeds: true } },
      },
      orderBy: { createdAt: 'desc' },
    }),
    prismaUnscoped.property.groupBy({ by: ['tenantId'], where: { isArchived: false }, _count: true }),
    prismaUnscoped.bed.groupBy({ by: ['tenantId', 'status'], where: { archivedAt: null }, _count: true }),
    prismaUnscoped.studentProfile.groupBy({ by: ['tenantId'], where: { residencyStatus: { not: 'VACATED' } }, _count: true }),
    prismaUnscoped.studentProfile.groupBy({ by: ['tenantId'], where: { bedId: { not: null } }, _count: true }),
    // Rent the hostels themselves collected through HostelCare: the money the
    // platform helps move, and the clearest sign a hostel is really using it.
    prismaUnscoped.payment.groupBy({ by: ['tenantId'], where: { status: 'CLEARED', paidAt: { gte: thisMonth } }, _sum: { amount: true } }),
    prismaUnscoped.payment.groupBy({ by: ['tenantId'], where: { status: 'CLEARED', paidAt: { gte: new Date(now.getTime() - 30 * DAY) } }, _count: true }),
    prismaUnscoped.subscriptionInvoice.findMany({
      where: { status: { notIn: [SubscriptionStatus.DRAFT, SubscriptionStatus.VOID] }, issueDate: { gte: yearAgo } },
      select: { amount: true, issueDate: true },
    }),
    prismaUnscoped.subscriptionPayment.findMany({ where: { paidAt: { gte: yearAgo } }, select: { amount: true, paidAt: true } }),
    outstanding(),
    prismaUnscoped.subscriptionInvoice.groupBy({
      by: ['tenantId'],
      where: { status: { notIn: [SubscriptionStatus.DRAFT, SubscriptionStatus.VOID] } },
      _max: { issueDate: true, periodEnd: true },
    }),
  ]);
  const [rentLastMonth, rentThisMonthTotal, collectedAll, billedAll, draftCount] = await Promise.all([
    prismaUnscoped.payment.aggregate({ where: { status: 'CLEARED', paidAt: { gte: lastMonth, lt: thisMonth } }, _sum: { amount: true } }),
    prismaUnscoped.payment.aggregate({ where: { status: 'CLEARED', paidAt: { gte: thisMonth } }, _sum: { amount: true } }),
    prismaUnscoped.subscriptionPayment.aggregate({ where: { invoiceId: { not: null } }, _sum: { amount: true } }),
    prismaUnscoped.subscriptionInvoice.aggregate({ where: { status: { notIn: [SubscriptionStatus.DRAFT, SubscriptionStatus.VOID] } }, _sum: { amount: true } }),
    prismaUnscoped.subscriptionInvoice.count({ where: { status: SubscriptionStatus.DRAFT } }),
  ]);

  const count = <T extends { tenantId: string; _count: number }>(rows: T[]) => new Map(rows.map((r) => [r.tenantId, r._count]));
  const props = count(propsBy);
  const residents = count(residentsBy);
  const housed = count(housedBy);
  const rentRecent = count(rentRecentBy);
  const rent = new Map(rentBy.map((r) => [r.tenantId, r._sum.amount ?? 0]));
  const beds = new Map<string, { total: number; occupied: number }>();
  for (const r of bedsBy) {
    const b = beds.get(r.tenantId) ?? { total: 0, occupied: 0 };
    b.total += r._count;
    if (r.status === 'OCCUPIED') b.occupied += r._count;
    beds.set(r.tenantId, b);
  }
  const issued = new Map(lastIssued.map((r) => [r.tenantId, r._max]));

  // ── Revenue ───────────────────────────────────────────────────────────────
  const active = tenants.filter((t) => t.status === TenantStatus.ACTIVE);
  const paying = active.filter((t) => (t.planRef?.monthlyPrice ?? 0) > 0);
  const mrr = paying.reduce((n, t) => n + t.planRef!.monthlyPrice, 0);
  const sumIn = <T extends { amount: number }>(rows: T[], at: (r: T) => Date | null, from: Date, to?: Date) =>
    rows.reduce((n, r) => {
      const d = at(r);
      return d && d >= from && (!to || d < to) ? n + r.amount : n;
    }, 0);
  const collectedThisMonth = sumIn(payments, (p) => p.paidAt, thisMonth);
  const collectedLastMonth = sumIn(payments, (p) => p.paidAt, lastMonth, thisMonth);
  const billedThisMonth = sumIn(invoices, (i) => i.issueDate, thisMonth);

  // ── 12-month trend ────────────────────────────────────────────────────────
  const months = Array.from({ length: 12 }, (_, i) => monthKey(monthStart(now, 11 - i)));
  const trend = months.map((m) => ({ month: m, billed: 0, collected: 0, newHostels: 0 }));
  const at = new Map(trend.map((t) => [t.month, t]));
  for (const i of invoices) if (i.issueDate) at.get(monthKey(i.issueDate))!.billed += i.amount;
  for (const p of payments) {
    const row = at.get(monthKey(p.paidAt));
    if (row) row.collected += p.amount;
  }
  for (const t of tenants) {
    const row = at.get(monthKey(t.createdAt));
    if (row) row.newHostels += 1;
  }

  // ── Hostels ───────────────────────────────────────────────────────────────
  const byKind = Object.fromEntries(Object.values(TenantKind).map((k) => [k, tenants.filter((t) => t.kind === k && t.status === TenantStatus.ACTIVE).length])) as Record<TenantKind, number>;
  const planMix = new Map<string, { planId: string | null; name: string; price: number; hostels: number; mrr: number }>();
  for (const t of active) {
    const key = t.planRef?.id ?? 'none';
    const row = planMix.get(key) ?? { planId: t.planRef?.id ?? null, name: t.planRef?.name ?? 'No plan', price: t.planRef?.monthlyPrice ?? 0, hostels: 0, mrr: 0 };
    row.hostels += 1;
    row.mrr += t.planRef?.monthlyPrice ?? 0;
    planMix.set(key, row);
  }

  // ── Platform usage ────────────────────────────────────────────────────────
  let bedTotal = 0;
  let bedOccupied = 0;
  for (const b of beds.values()) {
    bedTotal += b.total;
    bedOccupied += b.occupied;
  }
  const residentTotal = [...residents.values()].reduce((n, v) => n + v, 0);
  const housedTotal = [...housed.values()].reduce((n, v) => n + v, 0);
  const propertyTotal = [...props.values()].reduce((n, v) => n + v, 0);

  // ── Needs attention ───────────────────────────────────────────────────────
  // Due for invoicing: an active, paying hostel whose last issued invoice's
  // period ends within a week (or, without a period, was issued over 30 days
  // ago), or that has never been invoiced. Manual invoicing needs this nudge.
  const dueForInvoicing = paying
    .map((t) => {
      const last = issued.get(t.id);
      const periodEnd = last?.periodEnd ?? null;
      const issueDate = last?.issueDate ?? null;
      const due = !last
        ? true
        : periodEnd
          ? periodEnd.getTime() <= today.getTime() + 7 * DAY
          : !!issueDate && issueDate.getTime() <= today.getTime() - 30 * DAY;
      return due
        ? {
            tenantId: t.id,
            name: t.name,
            plan: t.planRef!.name,
            monthlyPrice: t.planRef!.monthlyPrice,
            lastIssued: issueDate,
            coveredUntil: periodEnd,
            reason: !last ? 'Never invoiced' : periodEnd ? (periodEnd < today ? 'Paid-for period has ended' : 'Period ends within a week') : 'No invoice in 30 days',
          }
        : null;
    })
    .filter((x): x is NonNullable<typeof x> => !!x)
    .sort((a, b) => (a.coveredUntil?.getTime() ?? 0) - (b.coveredUntil?.getTime() ?? 0));

  // Near plan limits: at or above 80% of beds, or at the property cap. These
  // are the upsell conversations.
  const nearLimits = active
    .map((t) => {
      const b = beds.get(t.id)?.total ?? 0;
      const p = props.get(t.id) ?? 0;
      const bedShare = t.planRef?.maxBeds ? b / t.planRef.maxBeds : 0;
      const propShare = t.planRef?.maxProperties ? p / t.planRef.maxProperties : 0;
      return { tenantId: t.id, name: t.name, plan: t.planRef?.name ?? 'No plan', beds: b, maxBeds: t.planRef?.maxBeds ?? null, properties: p, maxProperties: t.planRef?.maxProperties ?? null, share: Math.max(bedShare, propShare) };
    })
    .filter((x) => x.share >= 0.8)
    .sort((a, b) => b.share - a.share);

  // Quiet hostels: active for 30+ days with no rent recorded in the last 30.
  // A hostel that stops using the product is the earliest churn warning.
  const quiet = active
    .filter((t) => t.createdAt.getTime() < now.getTime() - 30 * DAY && !rentRecent.get(t.id))
    .map((t) => ({ tenantId: t.id, name: t.name, plan: t.planRef?.name ?? 'No plan', residents: residents.get(t.id) ?? 0, since: t.createdAt }));

  const overdue = open.invoices
    .filter((i) => i.overdue)
    .map((i) => ({
      invoiceId: i.id,
      invoiceNumber: i.invoiceNumber,
      tenantId: i.tenantId,
      name: i.tenant.name,
      balance: i.balance,
      dueDate: i.dueDate,
      daysOverdue: i.dueDate ? Math.max(1, Math.floor((today.getTime() - i.dueDate.getTime()) / DAY)) : 0,
    }))
    .sort((a, b) => b.daysOverdue - a.daysOverdue);

  const rentThisMonth = rentThisMonthTotal._sum.amount ?? 0;
  const topByRent = active
    .map((t) => ({ tenantId: t.id, name: t.name, kind: t.kind, rent: rent.get(t.id) ?? 0, residents: residents.get(t.id) ?? 0, beds: beds.get(t.id)?.total ?? 0 }))
    .filter((x) => x.rent > 0)
    .sort((a, b) => b.rent - a.rent)
    .slice(0, 5);

  return {
    generatedAt: now,
    revenue: {
      mrr,
      arr: mrr * 12,
      arpa: paying.length ? Math.round(mrr / paying.length) : 0,
      payingHostels: paying.length,
      collectedThisMonth,
      collectedLastMonth,
      collectedChange: change(collectedThisMonth, collectedLastMonth),
      collectedYtd: sumIn(payments, (p) => p.paidAt, yearStart),
      billedThisMonth,
      outstanding: open.totalOutstanding,
      outstandingCount: open.invoices.length,
      overdueAmount: open.overdueAmount,
      overdueCount: open.overdueCount,
      collectionRate: pct(collectedAll._sum.amount ?? 0, billedAll._sum.amount ?? 0),
      draftInvoices: draftCount,
    },
    hostels: {
      total: tenants.length,
      active: active.length,
      suspended: tenants.length - active.length,
      newThisMonth: tenants.filter((t) => t.createdAt >= thisMonth).length,
      newLastMonth: tenants.filter((t) => t.createdAt >= lastMonth && t.createdAt < thisMonth).length,
      suspendedThisMonth: tenants.filter((t) => t.suspendedAt && t.suspendedAt >= thisMonth).length,
      freeOrNoPlan: active.length - paying.length,
      byKind,
      planMix: [...planMix.values()].sort((a, b) => b.mrr - a.mrr || b.hostels - a.hostels),
    },
    usage: {
      properties: propertyTotal,
      beds: bedTotal,
      occupiedBeds: bedOccupied,
      occupancy: pct(bedOccupied, bedTotal),
      residents: residentTotal,
      housedResidents: housedTotal,
      rentThisMonth,
      rentLastMonth: rentLastMonth._sum.amount ?? 0,
      rentChange: change(rentThisMonth, rentLastMonth._sum.amount ?? 0),
    },
    trend,
    attention: {
      overdue: overdue.slice(0, 8),
      dueForInvoicing: dueForInvoicing.slice(0, 8),
      dueForInvoicingCount: dueForInvoicing.length,
      nearLimits: nearLimits.slice(0, 8),
      quiet: quiet.slice(0, 8),
      quietCount: quiet.length,
    },
    topByRent,
    recentHostels: tenants.slice(0, 5).map((t) => ({ tenantId: t.id, name: t.name, kind: t.kind, plan: t.planRef?.name ?? 'No plan', createdAt: t.createdAt, status: t.status })),
  };
}
