import { Router, Request, Response } from 'express';
import { Role, SubscriptionStatus } from '@prisma/client';
import { NotFoundError } from '../../lib/errors';
import { buildSubscriptionInvoicePdf } from '../subscriptions/subscription-invoice-pdf.service';
import { asyncHandler } from '../../middleware/asyncHandler';
import { authenticate } from '../../middleware/authenticate';
import { authorize } from '../../middleware/authorize';
import { hasFeature } from '../../lib/tenant-features';
import { requireFeature } from '../../middleware/requireFeature';
import { db, prismaUnscoped } from '../../lib/prisma';
import { getTenantIdOrThrow } from '../../lib/tenantContext';

/**
 * What the tenant's own plan allows, and how much of it they have used.
 *
 * The plan CRUD next door is Super Admin only — deliberately, since plans are
 * platform data. But a hostel admin still has to be able to see their own
 * ceiling, otherwise the first they hear of it is a create failing halfway
 * through a bulk import. This is read-only and reports only their own tenant.
 */
export const planUsageRouter = Router();
// Staff only: what the hostel pays the platform is not the student's business.
planUsageRouter.use(authenticate, authorize(Role.HOSTEL_ADMIN, Role.WARDEN, Role.MESS_ADMIN));

planUsageRouter.get(
  '/',
  asyncHandler(async (req: Request, res: Response) => {
    const tenantId = getTenantIdOrThrow();
    const tenant = await prismaUnscoped.tenant.findUnique({
      where: { id: tenantId },
      include: {
        planRef: {
          select: { name: true, monthlyPrice: true, features: true, isActive: true, maxProperties: true, maxBeds: true },
        },
      },
    });

    // What the hostel owes the platform. Owner-only: a warden runs the
    // hostel, but the platform bill is the owner's business.
    let subscription: null | {
      outstanding: number;
      invoices: {
        id: string;
        periodMonth: string;
        planName: string;
        amount: number;
        paid: number;
        status: string;
        dueDate: Date | null;
        invoiceNumber: string | null;
        invoiceType: string;
        issueDate: Date | null;
        periodStart: Date | null;
        periodEnd: Date | null;
      }[];
    } = null;
    // An Enterprise tenant sees no money, so neither the bill nor the price (6 Nov 2026).
    const showsMoney = hasFeature(tenant?.kind, 'billing');
    if (showsMoney && req.user!.role === Role.HOSTEL_ADMIN) {
      const invoices = await prismaUnscoped.subscriptionInvoice.findMany({
        // Drafts are not issued yet and cancelled ones are not owed.
        where: { tenantId, status: { notIn: [SubscriptionStatus.DRAFT, SubscriptionStatus.VOID] } },
        include: { payments: { select: { amount: true } } },
        orderBy: [{ issueDate: 'desc' }, { periodMonth: 'desc' }],
        take: 6,
      });
      const rows = invoices.map((i) => ({
        id: i.id,
        periodMonth: i.periodMonth,
        planName: i.planName,
        amount: i.amount,
        paid: i.payments.reduce((n, p) => n + p.amount, 0),
        status: i.status,
        dueDate: i.dueDate,
        invoiceNumber: i.invoiceNumber,
        invoiceType: i.invoiceType,
        issueDate: i.issueDate,
        periodStart: i.periodStart,
        periodEnd: i.periodEnd,
      }));
      subscription = { outstanding: rows.reduce((n, r) => n + Math.max(0, r.amount - r.paid), 0), invoices: rows };
    }

    // Counts come from the scoped client, so they cannot leak across tenants.
    const [properties, rooms, students, beds] = await Promise.all([
      db.property.count({}),
      db.room.count({ where: { archivedAt: null, floor: { not: null } } }),
      db.studentProfile.count({}),
      db.bed.count({ where: { archivedAt: null, room: { floor: { not: null } } } }),
    ]);

    res.json({
      usage: {
        // No plan, or a null limit on one, means unlimited — reported as null
        // rather than a number the client would have to special-case.
        plan: tenant?.planRef?.name ?? null,
        planDetails: showsMoney && tenant?.planRef
          ? {
              name: tenant.planRef.name,
              monthlyPrice: tenant.planRef.monthlyPrice,
              features: tenant.planRef.features,
              isActive: tenant.planRef.isActive,
            }
          : null,
        tenantKind: tenant?.kind ?? null,
        tenantSince: tenant?.createdAt ?? null,
        tenantStatus: tenant?.status ?? null,
        subscription,
        properties: { used: properties, max: tenant?.planRef?.maxProperties ?? null },
        beds: { used: beds, max: tenant?.planRef?.maxBeds ?? null },
        // No longer capped by any plan; still reported (unlimited) for older
        // app builds that draw these meters.
        rooms: { used: rooms, max: null },
        students: { used: students, max: null },
      },
    });
  }),
);

/**
 * The owner downloads one of their own issued platform invoices. Another
 * tenant's invoice, a draft or a cancelled one reads as not found.
 */
planUsageRouter.get(
  '/invoices/:id/pdf',
  authorize(Role.HOSTEL_ADMIN),
  requireFeature('billing'),
  asyncHandler(async (req: Request, res: Response) => {
    const inv = await prismaUnscoped.subscriptionInvoice.findUnique({ where: { id: req.params.id }, select: { tenantId: true, status: true } });
    if (!inv || inv.tenantId !== getTenantIdOrThrow() || inv.status === SubscriptionStatus.DRAFT || inv.status === SubscriptionStatus.VOID) {
      throw new NotFoundError('Invoice not found');
    }
    const { buffer, filename } = await buildSubscriptionInvoicePdf(req.params.id);
    res.setHeader('Content-Type', 'application/pdf');
    res.setHeader('Content-Disposition', `attachment; filename="${filename}"`);
    res.send(buffer);
  }),
);

