import { ChargeFrequency, InvoiceLineKind, InvoiceStatus, InvoiceType, LateFeeMode, PaymentStatus, Prisma } from '@prisma/client';
import { db, prismaUnscoped } from '../../lib/prisma';
import { getTenantIdOrThrow } from '../../lib/tenantContext';
import { monthRange, periodEnd } from '../../lib/period';
import { BadRequestError, ConflictError, NotFoundError } from '../../lib/errors';

/**
 * Billing rules: the four things Indian hostels charge that a flat monthly
 * rent does not express — days actually stayed, a fee for paying late,
 * charges besides rent, and GST above the exemption line.
 *
 * Every rule lives on the property and is OFF by default. A property that
 * sets none produces exactly the invoice it produced before: one amount, no
 * lines a client did not ask for. Invoice.amount remains the total; lines
 * are the explanation underneath it.
 */

const DAY_MS = 86_400_000;

// The scoped client is $extends-wrapped, so its transaction client is not
// Prisma.TransactionClient — derive the type from the client itself.
type Tx = Parameters<Parameters<typeof db.$transaction>[0]>[0];

export const BILLING_RULE_FIELDS = {
  prorataEnabled: true,
  lateFeeEnabled: true,
  lateFeeGraceDays: true,
  lateFeeMode: true,
  lateFeeAmount: true,
  lateFeeCap: true,
  gstEnabled: true,
  gstRate: true,
  gstThreshold: true,
  gstInclusive: true,
} as const;

export type BillingRules = Prisma.PropertyGetPayload<{ select: typeof BILLING_RULE_FIELDS }>;

export const DEFAULT_RULES: BillingRules = {
  prorataEnabled: false,
  lateFeeEnabled: false,
  lateFeeGraceDays: 5,
  lateFeeMode: LateFeeMode.FLAT,
  lateFeeAmount: 0,
  lateFeeCap: null,
  gstEnabled: false,
  gstRate: 12,
  gstThreshold: 20000,
  gstInclusive: false,
};

export async function getBillingRules(propertyId: string): Promise<BillingRules> {
  const p = await db.property.findFirst({ where: { id: propertyId }, select: BILLING_RULE_FIELDS });
  if (!p) throw new NotFoundError('Property not found');
  return p;
}

export async function updateBillingRules(propertyId: string, input: Partial<BillingRules>): Promise<BillingRules> {
  const existing = await db.property.findFirst({ where: { id: propertyId }, select: { id: true } });
  if (!existing) throw new NotFoundError('Property not found');
  if (input.lateFeeEnabled && (input.lateFeeAmount ?? 0) <= 0) {
    const current = await getBillingRules(propertyId);
    if ((input.lateFeeAmount ?? current.lateFeeAmount) <= 0) {
      throw new BadRequestError('Set a late fee amount before turning late fees on');
    }
  }
  return db.property.update({ where: { id: propertyId }, data: input, select: BILLING_RULE_FIELDS });
}

// ── Pro-rata ───────────────────────────────────────────────────────────────

/**
 * The calendar span an invoice covers: first day of periodMonth to the last
 * day of its last month, both as UTC midnights so day arithmetic is exact.
 */
export function cycleSpan(periodMonth: string, cycleMonths: number): { start: Date; end: Date; days: number } {
  const start = monthRange(periodMonth).start;
  const end = utcDay(monthRange(periodEnd(periodMonth, cycleMonths)).end);
  const days = Math.round((end.getTime() - start.getTime()) / DAY_MS) + 1;
  return { start, end, days };
}

/** Midnight UTC of a date's calendar day. */
export function utcDay(d: Date): Date {
  return new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate()));
}

/**
 * How much of a full-cycle amount a student who arrived on `movedIn` owes.
 * Whole cycle when they were already there; the days from move-in to the
 * end of the cycle, inclusive, when they arrived during it; nothing when
 * they arrive after it ends.
 */
export function prorataOnMoveIn(full: number, periodMonth: string, cycleMonths: number, movedIn: Date | null): { amount: number; coveredFrom: Date | null; days: number | null } {
  const span = cycleSpan(periodMonth, cycleMonths);
  if (!movedIn) return { amount: full, coveredFrom: null, days: null };
  const from = utcDay(movedIn);
  if (from <= span.start) return { amount: full, coveredFrom: null, days: null };
  if (from > span.end) return { amount: 0, coveredFrom: from, days: 0 };
  const days = Math.round((span.end.getTime() - from.getTime()) / DAY_MS) + 1;
  return { amount: Math.round((full * days) / span.days), coveredFrom: from, days };
}

// ── Charge types ───────────────────────────────────────────────────────────

export interface ChargeTypeInput {
  name: string;
  amount: number;
  frequency: ChargeFrequency;
  appliesToAll?: boolean;
  active?: boolean;
}

const chargeTypeInclude = { assignments: { select: { studentProfileId: true } }, _count: { select: { charges: true } } } as const;

/**
 * How often a type has been billed: one-off charges recorded against it, plus
 * the invoice lines generation wrote for it (which have no StudentCharge row).
 */
async function timesBilled(chargeTypeId: string, oneOffs: number): Promise<number> {
  const lines = await db.invoiceLine.count({ where: { kind: InvoiceLineKind.CHARGE, meta: { path: ['chargeTypeId'], equals: chargeTypeId } } });
  return oneOffs + lines;
}

async function publicChargeType(c: Prisma.ChargeTypeGetPayload<{ include: typeof chargeTypeInclude }>) {
  const { assignments, _count, ...rest } = c;
  return { ...rest, studentIds: assignments.map((a) => a.studentProfileId), usedCount: await timesBilled(c.id, _count.charges) };
}

export async function listChargeTypes(propertyId: string) {
  const rows = await db.chargeType.findMany({ where: { propertyId }, include: chargeTypeInclude, orderBy: { createdAt: 'asc' } });
  return Promise.all(rows.map(publicChargeType));
}

export async function createChargeType(propertyId: string, input: ChargeTypeInput) {
  const tenantId = getTenantIdOrThrow();
  const property = await db.property.findFirst({ where: { id: propertyId }, select: { id: true } });
  if (!property) throw new NotFoundError('Property not found');
  const clash = await db.chargeType.findFirst({ where: { propertyId, name: { equals: input.name.trim(), mode: 'insensitive' } } });
  if (clash) throw new ConflictError(`A charge called "${input.name.trim()}" already exists for this property`);
  const row = await db.chargeType.create({
    data: { tenantId, propertyId, name: input.name.trim(), amount: input.amount, frequency: input.frequency, appliesToAll: input.appliesToAll ?? true, active: input.active ?? true },
    include: chargeTypeInclude,
  });
  return publicChargeType(row);
}

export async function updateChargeType(id: string, input: Partial<ChargeTypeInput>) {
  const existing = await db.chargeType.findFirst({ where: { id } });
  if (!existing) throw new NotFoundError('Charge type not found');
  if (input.name && input.name.trim().toLowerCase() !== existing.name.toLowerCase()) {
    const clash = await db.chargeType.findFirst({ where: { propertyId: existing.propertyId, id: { not: id }, name: { equals: input.name.trim(), mode: 'insensitive' } } });
    if (clash) throw new ConflictError(`A charge called "${input.name.trim()}" already exists for this property`);
  }
  const row = await db.chargeType.update({
    where: { id },
    data: { ...input, ...(input.name ? { name: input.name.trim() } : {}) },
    include: chargeTypeInclude,
  });
  return publicChargeType(row);
}

/** Removing a charge type that has been billed would orphan history, so it is deactivated instead. */
export async function deleteChargeType(id: string) {
  const existing = await db.chargeType.findFirst({ where: { id }, include: { _count: { select: { charges: true } } } });
  if (!existing) throw new NotFoundError('Charge type not found');
  if ((await timesBilled(id, existing._count.charges)) > 0) {
    await db.chargeType.update({ where: { id }, data: { active: false } });
    return { deactivated: true };
  }
  await db.chargeType.delete({ where: { id } });
  return { deactivated: false };
}

/** Replace the set of students a selective charge applies to. */
export async function setChargeStudents(id: string, studentIds: string[]) {
  const tenantId = getTenantIdOrThrow();
  const existing = await db.chargeType.findFirst({ where: { id } });
  if (!existing) throw new NotFoundError('Charge type not found');
  const valid = await db.studentProfile.findMany({ where: { id: { in: studentIds }, propertyId: existing.propertyId }, select: { id: true } });
  const ids = valid.map((s) => s.id);
  await db.$transaction([
    db.chargeAssignment.deleteMany({ where: { chargeTypeId: id } }),
    ...(ids.length ? [db.chargeAssignment.createMany({ data: ids.map((studentProfileId) => ({ tenantId, chargeTypeId: id, studentProfileId })) })] : []),
    db.chargeType.update({ where: { id }, data: { appliesToAll: false } }),
  ]);
  const row = await db.chargeType.findFirst({ where: { id }, include: chargeTypeInclude });
  return publicChargeType(row!);
}

/**
 * The recurring charge lines a student's rent invoice carries this cycle:
 * MONTHLY charges once per month covered, PER_CYCLE charges once.
 */
export async function recurringChargeLines(propertyId: string, studentProfileId: string, cycleMonths: number) {
  const types = await db.chargeType.findMany({
    where: {
      propertyId,
      active: true,
      frequency: { in: [ChargeFrequency.MONTHLY, ChargeFrequency.PER_CYCLE] },
      OR: [{ appliesToAll: true }, { assignments: { some: { studentProfileId } } }],
    },
  });
  return types.map((t) => {
    const months = t.frequency === ChargeFrequency.MONTHLY ? Math.max(1, cycleMonths) : 1;
    return {
      kind: InvoiceLineKind.CHARGE,
      label: months > 1 ? `${t.name} × ${months} months` : t.name,
      amount: t.amount * months,
      meta: { chargeTypeId: t.id, months, unit: t.amount },
    };
  });
}

// ── One-off charges on a student ────────────────────────────────────────────

export interface StudentChargeInput {
  label: string;
  amount: number;
  chargeTypeId?: string;
  note?: string;
  date?: Date;
  /** True: raise a standalone invoice now. False: carry into the next rent invoice. */
  billNow: boolean;
  dueDate?: Date;
}

export async function listStudentCharges(studentProfileId: string) {
  return db.studentCharge.findMany({
    where: { studentProfileId },
    include: { chargeType: { select: { name: true } }, invoice: { select: { id: true, periodMonth: true, status: true, type: true } } },
    orderBy: { date: 'desc' },
  });
}

export async function addStudentCharge(studentProfileId: string, input: StudentChargeInput, createdById: string) {
  const tenantId = getTenantIdOrThrow();
  const student = await db.studentProfile.findFirst({ where: { id: studentProfileId }, select: { id: true, propertyId: true } });
  if (!student) throw new NotFoundError('Student not found');
  if (input.chargeTypeId) {
    const type = await db.chargeType.findFirst({ where: { id: input.chargeTypeId } });
    if (!type) throw new NotFoundError('Charge type not found');
  }
  const date = input.date ?? new Date();

  return db.$transaction(async (tx) => {
    const charge = await tx.studentCharge.create({
      data: { tenantId, studentProfileId, chargeTypeId: input.chargeTypeId, label: input.label.trim(), amount: input.amount, note: input.note, date, createdById },
    });
    if (!input.billNow) return { charge, invoice: null };

    // A standalone OTHER invoice for this month. Unique per student/type/month,
    // so a second one-off in the same month joins the existing open invoice.
    const periodMonth = date.toISOString().slice(0, 7);
    const existing = await tx.invoice.findFirst({ where: { studentProfileId, type: InvoiceType.OTHER, periodMonth } });
    let invoice;
    if (existing && existing.status !== InvoiceStatus.PAID) {
      invoice = await tx.invoice.update({
        where: { id: existing.id },
        data: { amount: { increment: input.amount }, status: existing.status === InvoiceStatus.PARTIAL ? InvoiceStatus.PARTIAL : InvoiceStatus.PENDING },
      });
    } else if (existing) {
      throw new ConflictError('This month already has a settled charges invoice; carry the charge into the next rent invoice instead');
    } else {
      invoice = await tx.invoice.create({
        data: { tenantId, studentProfileId, type: InvoiceType.OTHER, periodMonth, cycleMonths: 1, amount: input.amount, dueDate: input.dueDate ?? new Date(date.getTime() + 7 * DAY_MS) },
      });
    }
    await tx.invoiceLine.create({ data: { tenantId, invoiceId: invoice.id, kind: InvoiceLineKind.CHARGE, label: charge.label, amount: charge.amount, meta: { studentChargeId: charge.id, chargeTypeId: input.chargeTypeId ?? null } } });
    const linked = await tx.studentCharge.update({ where: { id: charge.id }, data: { invoiceId: invoice.id } });
    return { charge: linked, invoice };
  });
}

/** Un-invoiced one-off charges waiting for the student's next rent invoice. */
export async function pendingChargeLines(studentProfileId: string) {
  const rows = await db.studentCharge.findMany({ where: { studentProfileId, invoiceId: null }, orderBy: { date: 'asc' } });
  return rows.map((c) => ({ kind: InvoiceLineKind.CHARGE, label: c.label, amount: c.amount, meta: { studentChargeId: c.id, chargeTypeId: c.chargeTypeId }, studentChargeId: c.id }));
}

// ── GST ────────────────────────────────────────────────────────────────────

/**
 * Entry 12AA: hostel accommodation is exempt when it costs up to the
 * threshold per person per month. Above it, the whole supply is taxed.
 * Applied to the monthly rent, not to the pro-rated figure, because the
 * exemption is about the rate charged, not the days stayed.
 */
/**
 * GST on an amount, either way round (27 Oct 2026). On top: a GST line of
 * base × rate. Included: no line; the tax is the part of the price that is
 * GST — base × rate / (100 + rate) — kept to the paisa for the invoice.
 */
export function gstSplit(rules: Pick<BillingRules, 'gstRate' | 'gstInclusive'>, base: number) {
  const rate = rules.gstRate;
  if (rules.gstInclusive) {
    const taxPaise = Math.round((base * 100 * rate) / (100 + rate));
    return { inclusive: true as const, rate, taxPaise, taxAmount: Math.round(taxPaise / 100), line: null };
  }
  const amount = Math.round((base * rate) / 100);
  return { inclusive: false as const, rate, taxPaise: amount * 100, taxAmount: amount, line: amount > 0 ? { kind: InvoiceLineKind.GST, label: `GST @ ${rate}%`, amount, meta: { rate, base } } : null };
}

export function gstLine(rules: Pick<BillingRules, 'gstEnabled' | 'gstRate' | 'gstThreshold'>, monthlyRent: number, taxableBase: number) {
  if (!rules.gstEnabled || taxableBase <= 0 || monthlyRent <= rules.gstThreshold) return null;
  const amount = Math.round((taxableBase * rules.gstRate) / 100);
  if (amount <= 0) return null;
  return { kind: InvoiceLineKind.GST, label: `GST @ ${rules.gstRate}%`, amount, meta: { rate: rules.gstRate, base: taxableBase } };
}

// ── Late fees ──────────────────────────────────────────────────────────────

export interface LateFeeRunResult {
  propertiesChecked: number;
  invoicesCharged: number;
  totalAdded: number;
}

/**
 * Add late fees to overdue invoices. Runs on the hourly tick with no
 * request context (hence the unscoped client and explicit tenant), and
 * from the Settings "run now" button inside one.
 *
 * FLAT adds the fee once, the first day after grace. DAILY adds fee × days
 * since the last application (so a missed tick catches up rather than
 * forgetting days). Both stop at the cap. One pass per day per invoice.
 */
export async function applyLateFees(tenantId: string, today = utcDay(new Date())): Promise<LateFeeRunResult> {
  const result: LateFeeRunResult = { propertiesChecked: 0, invoicesCharged: 0, totalAdded: 0 };
  const properties = await prismaUnscoped.property.findMany({
    where: { tenantId, lateFeeEnabled: true, lateFeeAmount: { gt: 0 } },
    select: { id: true, ...BILLING_RULE_FIELDS },
  });

  for (const p of properties) {
    result.propertiesChecked++;
    const graceEnd = (due: Date) => new Date(utcDay(due).getTime() + p.lateFeeGraceDays * DAY_MS);
    const candidates = await prismaUnscoped.invoice.findMany({
      where: {
        tenantId,
        status: { not: InvoiceStatus.PAID },
        dueDate: { not: null, lt: new Date(today.getTime() - p.lateFeeGraceDays * DAY_MS) },
        student: { propertyId: p.id },
        OR: [{ lateFeeAppliedOn: null }, { lateFeeAppliedOn: { lt: today } }],
      },
      include: { lines: { where: { kind: InvoiceLineKind.LATE_FEE } }, payments: { where: { status: PaymentStatus.CLEARED }, select: { amount: true } } },
    });

    for (const inv of candidates) {
      const paid = inv.payments.reduce((n, x) => n + x.amount, 0);
      if (paid >= inv.amount) continue;
      const already = inv.lines.reduce((n, l) => n + l.amount, 0);
      const firstDay = graceEnd(inv.dueDate!);
      let fee = 0;
      let days = 0;
      if (p.lateFeeMode === LateFeeMode.FLAT) {
        if (already > 0) continue;
        fee = p.lateFeeAmount;
        days = 1;
      } else {
        const since = inv.lateFeeAppliedOn ? utcDay(inv.lateFeeAppliedOn) : firstDay;
        days = Math.max(0, Math.round((today.getTime() - since.getTime()) / DAY_MS));
        if (!inv.lateFeeAppliedOn) days += 1; // the first overdue day counts
        fee = p.lateFeeAmount * days;
      }
      if (p.lateFeeCap != null) fee = Math.max(0, Math.min(fee, p.lateFeeCap - already));
      if (fee <= 0) {
        await prismaUnscoped.invoice.update({ where: { id: inv.id }, data: { lateFeeAppliedOn: today } });
        continue;
      }
      await prismaUnscoped.$transaction([
        prismaUnscoped.invoiceLine.create({
          data: { tenantId, invoiceId: inv.id, kind: InvoiceLineKind.LATE_FEE, label: days > 1 ? `Late fee · ${days} days` : 'Late fee', amount: fee, meta: { days, mode: p.lateFeeMode, perDay: p.lateFeeAmount, on: today.toISOString().slice(0, 10) } },
        }),
        prismaUnscoped.invoice.update({ where: { id: inv.id }, data: { amount: { increment: fee }, lateFeeAppliedOn: today } }),
      ]);
      result.invoicesCharged++;
      result.totalAdded += fee;
    }
  }
  return result;
}

/** Every tenant with a property that charges late fees — the hourly tick. */
export async function applyLateFeesEverywhere(): Promise<void> {
  const tenants = await prismaUnscoped.property.findMany({ where: { lateFeeEnabled: true }, select: { tenantId: true }, distinct: ['tenantId'] });
  for (const t of tenants) {
    try {
      await applyLateFees(t.tenantId);
    } catch (err) {
      // eslint-disable-next-line no-console
      console.error(`Late-fee pass failed for tenant ${t.tenantId}:`, err);
    }
  }
}

// ── Move-out credit ────────────────────────────────────────────────────────

/**
 * When a student leaves mid-cycle under pro-rata, give back the unused days
 * of the current rent invoice. The credit never exceeds what is still owed:
 * money already paid is the settlement's business (Sprint 4), not a negative
 * invoice.
 */
export async function applyMoveOutCredit(tx: Tx, studentProfileId: string, vacatedOn: Date): Promise<{ credited: number; invoiceId: string | null }> {
  const tenantId = getTenantIdOrThrow();
  const student = await tx.studentProfile.findFirst({ where: { id: studentProfileId }, select: { propertyId: true } });
  if (!student?.propertyId) return { credited: 0, invoiceId: null };
  const property = await tx.property.findFirst({ where: { id: student.propertyId }, select: { prorataEnabled: true } });
  if (!property?.prorataEnabled) return { credited: 0, invoiceId: null };

  const day = utcDay(vacatedOn);
  const invoices = await tx.invoice.findMany({
    where: { studentProfileId, type: InvoiceType.RENT, status: { not: InvoiceStatus.PAID } },
    include: { lines: true, payments: { where: { status: PaymentStatus.CLEARED }, select: { amount: true } } },
    orderBy: { periodMonth: 'desc' },
  });
  const current = invoices.find((i) => {
    const span = cycleSpan(i.periodMonth, i.cycleMonths);
    return day >= span.start && day < span.end;
  });
  if (!current) return { credited: 0, invoiceId: null };
  // Credited once: a settlement may apply it before the bed is freed.
  if (current.lines.some((l) => l.kind === InvoiceLineKind.PRORATA_CREDIT)) return { credited: 0, invoiceId: current.id };

  const span = cycleSpan(current.periodMonth, current.cycleMonths);
  const from = current.coveredFrom ? utcDay(current.coveredFrom) : span.start;
  const totalDays = Math.round((span.end.getTime() - from.getTime()) / DAY_MS) + 1;
  const unusedDays = Math.round((span.end.getTime() - day.getTime()) / DAY_MS);
  if (unusedDays <= 0 || totalDays <= 0) return { credited: 0, invoiceId: current.id };

  const rentLine = current.lines.find((l) => l.kind === InvoiceLineKind.RENT);
  const rentAmount = rentLine?.amount ?? current.amount;
  const paid = current.payments.reduce((n, p) => n + p.amount, 0);
  const balance = current.amount - paid;
  const credit = Math.min(Math.round((rentAmount * unusedDays) / totalDays), Math.max(0, balance));
  if (credit <= 0) return { credited: 0, invoiceId: current.id };

  const newAmount = current.amount - credit;
  await tx.invoiceLine.create({
    data: { tenantId, invoiceId: current.id, kind: InvoiceLineKind.PRORATA_CREDIT, label: `Moved out ${day.toISOString().slice(0, 10)} · ${unusedDays} unused days`, amount: -credit, meta: { unusedDays, totalDays, vacatedOn: day.toISOString().slice(0, 10) } },
  });
  await tx.invoice.update({
    where: { id: current.id },
    data: {
      amount: newAmount,
      coveredTo: day,
      ...(paid >= newAmount ? { status: InvoiceStatus.PAID, paidAt: new Date() } : {}),
    },
  });
  return { credited: credit, invoiceId: current.id };
}
