import { InvoiceLineKind, InvoiceStatus, PaymentStatus } from '@prisma/client';
import { db } from '../../lib/prisma';
import { getTenantIdOrThrow } from '../../lib/tenantContext';
import { gstSplit } from '../billing/billing-rules.service';

/**
 * GST on dormitory stay invoices (27 Oct 2026). A stay invoice is all
 * accommodation — nights, early check-in, late check-out, extra nights — so
 * when the property charges GST the whole invoice is taxed:
 *
 * - prices include GST (`gstInclusive`): the total stays what the desk
 *   quoted, and the invoice records the GST inside it to the paisa;
 * - otherwise a GST line is added on top.
 *
 * The monthly exemption threshold is for hostel rent, so it is not applied
 * to nights. A property with GST off gets exactly the invoices it got before.
 *
 * Called after every change to a stay invoice; it recomputes from the lines,
 * so it is safe to run any number of times.
 */

type Rules = { gstEnabled: boolean; gstRate: number; gstInclusive: boolean };

async function rulesFor(propertyId: string): Promise<Rules | null> {
  return db.property.findFirst({ where: { id: propertyId }, select: { gstEnabled: true, gstRate: true, gstInclusive: true } });
}

/** What a base amount comes to with this property's GST: the invoice total. */
export async function taxedTotal(propertyId: string, base: number) {
  const r = await rulesFor(propertyId);
  if (!r?.gstEnabled || r.gstRate <= 0 || base <= 0 || r.gstInclusive) return base;
  return base + gstSplit(r, base).taxAmount;
}

export async function applyStayTax(invoiceId: string | null | undefined, propertyId: string) {
  if (!invoiceId) return;
  const inv = await db.invoice.findFirst({ where: { id: invoiceId }, include: { lines: true, payments: { where: { status: PaymentStatus.CLEARED }, select: { amount: true } } } });
  if (!inv) return;
  const r = await rulesFor(propertyId);
  const gstLines = inv.lines.filter((l) => l.kind === InvoiceLineKind.GST);
  const base = inv.lines.filter((l) => l.kind !== InvoiceLineKind.GST).reduce((n, l) => n + l.amount, 0);
  const taxed = !!r?.gstEnabled && r.gstRate > 0 && base > 0;
  // Nothing to do for an untaxed invoice that was never taxed: leave it exactly as it is.
  if (!taxed && !gstLines.length && !inv.taxRate) return;

  if (gstLines.length) await db.invoiceLine.deleteMany({ where: { id: { in: gstLines.map((l) => l.id) } } });
  const split = taxed ? gstSplit(r!, base) : null;
  if (split?.line) await db.invoiceLine.create({ data: { tenantId: getTenantIdOrThrow(), invoiceId, ...split.line } });
  const amount = base + (split && !split.inclusive ? split.taxAmount : 0);
  const paid = inv.payments.reduce((n, p) => n + p.amount, 0);
  await db.invoice.update({
    where: { id: invoiceId },
    data: {
      amount,
      taxAmount: split?.taxAmount ?? 0,
      taxInclusive: split?.inclusive ?? false,
      taxRate: split ? split.rate : null,
      taxPaise: split ? split.taxPaise : null,
      status: paid >= amount && amount > 0 ? InvoiceStatus.PAID : paid > 0 ? InvoiceStatus.PARTIAL : InvoiceStatus.PENDING,
      ...(paid >= amount && amount > 0 && inv.status !== InvoiceStatus.PAID ? { paidAt: new Date() } : {}),
    },
  });
}
