import { BedStatus, InvoiceStatus, PaymentStatus, Role, SubscriptionStatus } from '@prisma/client';
import { prismaUnscoped } from '../../lib/prisma';
import { NotFoundError } from '../../lib/errors';
import { accessSummary, istToday } from './tenant-access.service';

/**
 * Everything the super admin's tenant page shows (10 Oct 2026), in one read:
 * the account and its access window, a KPI strip, properties with their
 * occupancy, the people on the account, the plan against its limits, the
 * subscription billing position, and the hostel's own setup at a glance.
 * SUPER_ADMIN only, so it reads across the tenant with the unscoped client
 * and carries the tenant id on every query.
 */

const DAY = 86_400_000;
const IST_MS = 330 * 60_000;
const STAFF_ROLES = [Role.HOSTEL_ADMIN, Role.WARDEN, Role.MESS_ADMIN, Role.GUARD];

/** First instant of this India calendar month. */
function monthStart(now: Date) {
  const s = new Date(now.getTime() + IST_MS);
  return new Date(Date.UTC(s.getUTCFullYear(), s.getUTCMonth(), 1) - IST_MS);
}

export async function tenantOverview(tenantId: string, now = new Date()) {
  const t = await prismaUnscoped.tenant.findUnique({
    where: { id: tenantId },
    include: { planRef: { select: { id: true, name: true, monthlyPrice: true, maxProperties: true, maxBeds: true, features: true } }, settings: true },
  });
  if (!t) throw new NotFoundError('Tenant not found');
  const where = { tenantId };
  const thisMonth = monthStart(now);

  const [properties, rooms, beds, bedsByProperty, roomsByProperty, students, people, collected, openInvoices, subInvoices, subPayments] = await Promise.all([
    prismaUnscoped.property.findMany({ where, orderBy: { createdAt: 'asc' }, select: { id: true, name: true, city: true, state: true, address: true, isArchived: true, pricingMode: true, floors: true, createdAt: true } }),
    prismaUnscoped.room.count({ where: { ...where, archivedAt: null, floor: { not: null } } }),
    prismaUnscoped.bed.groupBy({ by: ['status'], where: { ...where, archivedAt: null, room: { floor: { not: null } } }, _count: { _all: true } }),
    // Beds belong to rooms, rooms to properties.
    prismaUnscoped.$queryRaw<{ propertyId: string; status: BedStatus; n: bigint }[]>`SELECT r."propertyId" AS "propertyId", b."status" AS status, count(*) AS n FROM "Bed" b JOIN "Room" r ON r."id" = b."roomId" WHERE b."tenantId" = ${tenantId} AND b."archivedAt" IS NULL AND r."floor" IS NOT NULL GROUP BY 1, 2`,
    prismaUnscoped.room.groupBy({ by: ['propertyId'], where: { ...where, archivedAt: null, floor: { not: null } }, _count: { _all: true } }),
    prismaUnscoped.studentProfile.count({ where }),
    prismaUnscoped.user.findMany({
      where: { tenantId, role: { in: STAFF_ROLES } },
      orderBy: [{ role: 'asc' }, { createdAt: 'asc' }],
      select: { id: true, name: true, email: true, phone: true, role: true, lastLoginAt: true, deactivatedAt: true, createdAt: true },
    }),
    prismaUnscoped.payment.aggregate({ where: { tenantId, status: PaymentStatus.CLEARED, paidAt: { gte: thisMonth } }, _sum: { amount: true } }),
    prismaUnscoped.invoice.findMany({ where: { tenantId, status: { in: [InvoiceStatus.PENDING, InvoiceStatus.PARTIAL] } }, select: { amount: true, payments: { where: { status: PaymentStatus.CLEARED }, select: { amount: true } } } }),
    prismaUnscoped.subscriptionInvoice.findMany({
      where: { tenantId, status: { not: SubscriptionStatus.VOID } },
      orderBy: [{ issueDate: 'desc' }, { createdAt: 'desc' }],
      take: 12,
      select: { id: true, invoiceNumber: true, invoiceType: true, planName: true, amount: true, status: true, issueDate: true, dueDate: true, periodStart: true, periodEnd: true, sentAt: true, payments: { select: { amount: true } } },
    }),
    prismaUnscoped.subscriptionPayment.findMany({ where, orderBy: { paidAt: 'desc' }, take: 8, select: { id: true, amount: true, method: true, reference: true, paidAt: true, invoice: { select: { invoiceNumber: true } } } }),
  ]);

  const bedCount = beds.reduce((n, b) => n + b._count._all, 0);
  const occupied = beds.find((b) => b.status === BedStatus.OCCUPIED)?._count._all ?? 0;
  const dues = openInvoices.reduce((n, i) => n + Math.max(0, i.amount - i.payments.reduce((m, p) => m + p.amount, 0)), 0);
  const invoices = subInvoices.map(({ payments, ...i }) => ({ ...i, paid: payments.reduce((n, p) => n + p.amount, 0), balance: Math.max(0, i.amount - payments.reduce((n, p) => n + p.amount, 0)) }));
  const owed = invoices.filter((i) => i.status !== SubscriptionStatus.DRAFT);
  const s = t.settings;
  const lastActive = people.reduce<Date | null>((d, p) => (p.lastLoginAt && (!d || p.lastLoginAt > d) ? p.lastLoginAt : d), null);

  return {
    tenant: {
      id: t.id,
      name: t.name,
      kind: t.kind,
      status: t.status,
      suspendedAt: t.suspendedAt,
      suspendedReason: t.suspendedReason,
      suspendedCause: t.suspendedCause,
      createdAt: t.createdAt,
      lastActiveAt: lastActive,
    },
    access: accessSummary(t, now),
    kpis: {
      properties: properties.filter((p) => !p.isArchived).length,
      rooms,
      beds: bedCount,
      occupied,
      occupancy: bedCount ? Math.round((occupied / bedCount) * 100) : null,
      students,
      staff: people.filter((p) => !p.deactivatedAt).length,
      collectedThisMonth: collected._sum.amount ?? 0,
      duesOutstanding: dues,
    },
    properties: properties.map((p) => {
      const mine = bedsByProperty.filter((b) => b.propertyId === p.id);
      const total = mine.reduce((n, b) => n + Number(b.n), 0);
      const occ = Number(mine.find((b) => b.status === BedStatus.OCCUPIED)?.n ?? 0);
      return { ...p, rooms: roomsByProperty.find((r) => r.propertyId === p.id)?._count._all ?? 0, beds: total, occupied: occ, occupancy: total ? Math.round((occ / total) * 100) : null };
    }),
    people,
    plan: t.planRef
      ? {
          ...t.planRef,
          usage: { properties: properties.length, beds: bedCount },
        }
      : null,
    billing: {
      invoices,
      payments: subPayments.map((p) => ({ ...p, invoiceNumber: p.invoice?.invoiceNumber ?? null, invoice: undefined })),
      billed: owed.reduce((n, i) => n + i.amount, 0),
      collected: owed.reduce((n, i) => n + i.paid, 0),
      outstanding: owed.reduce((n, i) => n + i.balance, 0),
      overdue: owed.filter((i) => i.balance > 0 && i.dueDate && i.dueDate.getTime() < now.getTime() - DAY).reduce((n, i) => n + i.balance, 0),
      profile: {
        firmName: s?.billingFirmName ?? null,
        gstin: s?.billingGstin ?? null,
        email: s?.billingEmail ?? null,
        phone: s?.billingPhone ?? null,
        address: s?.billingAddress ?? null,
      },
    },
    setup: {
      remindersEnabled: s?.remindersEnabled ?? false,
      reminderDaysBefore: s?.reminderDaysBefore ?? [],
      onlineCollectionEnabled: s?.onlineCollectionEnabled ?? false,
      virtualAccountsEnabled: s?.virtualAccountsEnabled ?? false,
      notifyPaymentEmail: s?.notifyPaymentEmail ?? true,
      notifyInvoiceEmail: s?.notifyInvoiceEmail ?? true,
      notifyNoticeEmail: s?.notifyNoticeEmail ?? true,
      messMonthlyFee: s?.messMonthlyFee ?? 0,
    },
    today: istToday(now),
  };
}
