import { InvoiceType, PaymentStatus } from '@prisma/client';
import { db } from '../../lib/prisma';
import { monthRange } from '../../lib/period';

/**
 * A month of the hostel's books as Tally vouchers (Sprint 6).
 *
 * Three voucher types, the way an accountant would key them in:
 *   Sales    — one per invoice raised for the period: Dr the student,
 *              Cr Rent/Mess/Other Income (and GST Payable when taxed);
 *   Receipt  — one per cleared payment in the month: Dr Cash or Bank,
 *              Cr the student;
 *   Payment  — one per expense dated in the month: Dr the category's
 *              expense ledger, Cr Cash.
 *
 * Ledger masters travel in the same file so a fresh company imports cleanly.
 * Amounts follow Tally's sign convention: a debit is negative with
 * ISDEEMEDPOSITIVE Yes, a credit positive with No. The CSV is the same rows
 * flattened to one line per ledger entry, for anyone who imports by sheet.
 */

interface Entry {
  ledger: string;
  debit: number;
  credit: number;
}
interface Voucher {
  type: 'Sales' | 'Receipt' | 'Payment';
  number: string;
  date: Date;
  narration: string;
  entries: Entry[];
}

const GROUPS = {
  student: 'Sundry Debtors',
  income: 'Direct Incomes',
  tax: 'Duties & Taxes',
  cash: 'Cash-in-Hand',
  bank: 'Bank Accounts',
  expense: 'Indirect Expenses',
} as const;

const incomeLedger = (t: InvoiceType) => (t === InvoiceType.RENT ? 'Rent Income' : t === InvoiceType.MESS ? 'Mess Income' : 'Other Income');
const titleCase = (s: string) => s.toLowerCase().replace(/_/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase());
const studentLedger = (name: string) => `${name.replace(/\s+/g, ' ').trim()} (Student)`;

export async function buildTally(period: string) {
  const { start, end } = monthRange(period);
  const settings = await db.tenantSettings.findFirst({ select: { billingFirmName: true } });
  const firm = settings?.billingFirmName?.trim() || 'HostelCare';

  const [invoices, payments, expenses] = await Promise.all([
    db.invoice.findMany({ where: { periodMonth: period }, include: { student: { include: { user: { select: { name: true } } } } }, orderBy: { createdAt: 'asc' } }),
    db.payment.findMany({ where: { paidAt: { gte: start, lte: end }, status: PaymentStatus.CLEARED }, include: { invoice: { include: { student: { include: { user: { select: { name: true } } } } } } }, orderBy: { paidAt: 'asc' } }),
    db.expense.findMany({ where: { date: { gte: start, lte: end } }, orderBy: { date: 'asc' } }),
  ]);

  const ledgers = new Map<string, string>(); // name → parent group
  const ledger = (name: string, group: string) => {
    ledgers.set(name, group);
    return name;
  };
  const vouchers: Voucher[] = [];
  let n = 0;

  for (const inv of invoices) {
    const who = ledger(studentLedger(inv.student.user.name), GROUPS.student);
    const tax = inv.taxAmount ?? 0;
    const entries: Entry[] = [{ ledger: who, debit: inv.amount, credit: 0 }, { ledger: ledger(incomeLedger(inv.type), GROUPS.income), debit: 0, credit: inv.amount - tax }];
    if (tax > 0) entries.push({ ledger: ledger('GST Payable', GROUPS.tax), debit: 0, credit: tax });
    vouchers.push({ type: 'Sales', number: `HC-S-${period}-${++n}`, date: inv.createdAt, narration: `${titleCase(inv.type)} invoice ${period} · ${inv.student.user.name}`, entries });
  }
  for (const p of payments) {
    const who = ledger(studentLedger(p.invoice.student.user.name), GROUPS.student);
    const into = p.method === 'CASH' ? ledger('Cash', GROUPS.cash) : ledger('Bank', GROUPS.bank);
    vouchers.push({ type: 'Receipt', number: `HC-R-${period}-${++n}`, date: p.paidAt, narration: `${titleCase(p.method)} received · ${p.invoice.student.user.name} · ${p.invoice.periodMonth}${p.note ? ` · ${p.note}` : ''}`, entries: [{ ledger: into, debit: p.amount, credit: 0 }, { ledger: who, debit: 0, credit: p.amount }] });
  }
  for (const e of expenses) {
    const exp = ledger(`${titleCase(e.category)} Expenses`, GROUPS.expense);
    vouchers.push({ type: 'Payment', number: `HC-P-${period}-${++n}`, date: e.date, narration: e.note ?? titleCase(e.category), entries: [{ ledger: exp, debit: e.amount, credit: 0 }, { ledger: ledger('Cash', GROUPS.cash), debit: 0, credit: e.amount }] });
  }
  return { firm, period, ledgers, vouchers, counts: { sales: invoices.length, receipts: payments.length, payments: expenses.length } };
}

const esc = (s: string) => s.replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&apos;' })[c]!);
const tallyDate = (d: Date) => d.toISOString().slice(0, 10).replace(/-/g, '');

export function tallyXml(b: Awaited<ReturnType<typeof buildTally>>): string {
  const masters = [...b.ledgers.entries()]
    .map(([name, parent]) => `<TALLYMESSAGE xmlns:UDF="TallyUDF"><LEDGER NAME="${esc(name)}" ACTION="Create"><NAME.LIST><NAME>${esc(name)}</NAME></NAME.LIST><PARENT>${esc(parent)}</PARENT>${parent === GROUPS.student ? '<ISBILLWISEON>No</ISBILLWISEON>' : ''}</LEDGER></TALLYMESSAGE>`)
    .join('\n');
  const vouchers = b.vouchers
    .map((v) => {
      const entries = v.entries
        .map((e) => {
          const debit = e.debit > 0;
          const amount = debit ? -e.debit : e.credit;
          return `<ALLLEDGERENTRIES.LIST><LEDGERNAME>${esc(e.ledger)}</LEDGERNAME><ISDEEMEDPOSITIVE>${debit ? 'Yes' : 'No'}</ISDEEMEDPOSITIVE><AMOUNT>${amount}</AMOUNT></ALLLEDGERENTRIES.LIST>`;
        })
        .join('');
      return `<TALLYMESSAGE xmlns:UDF="TallyUDF"><VOUCHER VCHTYPE="${v.type}" ACTION="Create"><DATE>${tallyDate(v.date)}</DATE><EFFECTIVEDATE>${tallyDate(v.date)}</EFFECTIVEDATE><VOUCHERTYPENAME>${v.type}</VOUCHERTYPENAME><VOUCHERNUMBER>${esc(v.number)}</VOUCHERNUMBER><NARRATION>${esc(v.narration)}</NARRATION><PERSISTEDVIEW>Accounting Voucher View</PERSISTEDVIEW>${entries}</VOUCHER></TALLYMESSAGE>`;
    })
    .join('\n');
  return `<?xml version="1.0" encoding="UTF-8"?>
<ENVELOPE>
<HEADER><TALLYREQUEST>Import Data</TALLYREQUEST></HEADER>
<BODY><IMPORTDATA>
<REQUESTDESC><REPORTNAME>Vouchers</REPORTNAME><STATICVARIABLES><SVCURRENTCOMPANY>${esc(b.firm)}</SVCURRENTCOMPANY></STATICVARIABLES></REQUESTDESC>
<REQUESTDATA>
${masters}
${vouchers}
</REQUESTDATA>
</IMPORTDATA></BODY>
</ENVELOPE>
`;
}

/** One line per ledger entry: the same vouchers as a sheet. */
export function tallyCsv(b: Awaited<ReturnType<typeof buildTally>>): string {
  const cell = (v: unknown) => {
    const s = v == null ? '' : String(v);
    return /[",\r\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
  };
  const rows: string[] = ['date,voucherType,voucherNo,ledger,group,debit,credit,narration'];
  for (const v of b.vouchers) {
    for (const e of v.entries) {
      rows.push([v.date.toISOString().slice(0, 10), v.type, v.number, e.ledger, b.ledgers.get(e.ledger) ?? '', e.debit || '', e.credit || '', v.narration].map(cell).join(','));
    }
  }
  return `﻿${rows.join('\r\n')}\r\n`;
}
