import { Router, Request, Response } from 'express';
import { z } from 'zod';
import { Role, TenantKind } from '@prisma/client';
import { asyncHandler } from '../../middleware/asyncHandler';
import { authenticate } from '../../middleware/authenticate';
import { authorize } from '../../middleware/authorize';
import { requireFeature, tenantHasFeature, tenantKindOf } from '../../middleware/requireFeature';
import { db, prismaUnscoped } from '../../lib/prisma';
import { getTenantIdOrThrow } from '../../lib/tenantContext';
import { BadRequestError, ConflictError, ForbiddenError, NotFoundError } from '../../lib/errors';
import { isValidPeriod } from '../../lib/period';
import { buildTally, tallyCsv, tallyXml } from './tally.service';

/**
 * A hostel's own account: taking its data out, and asking to leave.
 *
 * Both are HOSTEL_ADMIN only — a warden can run the hostel but does not own
 * it. Export reads through the scoped client so it can only ever contain this
 * tenant's rows. Deletion is a REQUEST: the super admin decides, and the
 * request row is the audit trail that a human asked and a human answered.
 */

export const accountRouter = Router();
accountRouter.use(authenticate, authorize(Role.HOSTEL_ADMIN));

// ── Export ──────────────────────────────────────────────────────────────────

/** RFC 4180-ish: quote everything that needs it, CRLF rows, UTF-8 BOM so
 *  Excel opens ₹ and Indian names correctly instead of as mojibake. */
function toCsv(rows: Record<string, unknown>[], columns: string[]): string {
  const cell = (v: unknown) => {
    if (v == null) return '';
    const s = v instanceof Date ? v.toISOString() : String(v);
    return /[",\r\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
  };
  const lines = [columns.join(','), ...rows.map((r) => columns.map((c) => cell(r[c])).join(','))];
  return `\uFEFF${lines.join('\r\n')}\r\n`;
}

const DATASETS = ['students', 'rooms', 'invoices', 'payments', 'expenses', 'mess-stock', 'complaints'] as const;
type Dataset = (typeof DATASETS)[number];
/** Money itself: not offered where no money is shown (Enterprise). */
const MONEY_DATASETS: Dataset[] = ['invoices', 'payments', 'expenses'];

async function buildDataset(name: Dataset): Promise<{ rows: Record<string, unknown>[]; columns: string[] }> {
  switch (name) {
    case 'students': {
      const rows = await db.studentProfile.findMany({
        include: {
          user: { select: { name: true, email: true, phone: true } },
          bed: { include: { room: { select: { number: true } } } },
          property: { select: { name: true } },
        },
        orderBy: { createdAt: 'asc' },
      });
      const employee = (await tenantKindOf(getTenantIdOrThrow())) === TenantKind.ENTERPRISE;
      return {
        columns: employee
          ? ['name', 'email', 'phone', 'property', 'room', 'bed', 'guardianName', 'guardianPhone', 'parentName', 'parentPhone', 'address', 'city', 'state', 'postalCode', 'kycIdType', 'kycStatus', 'policeVerificationStatus', 'joinedAt']
          : ['name', 'email', 'phone', 'property', 'room', 'bed', 'guardianName', 'guardianPhone', 'address', 'city', 'state', 'postalCode', 'depositAmount', 'depositPaid', 'depositRefunded', 'kycIdType', 'kycStatus', 'policeVerificationStatus', 'joinedAt'],
        rows: rows.map((s) => ({
          name: s.user.name, email: s.user.email, phone: s.user.phone,
          property: s.property?.name, room: s.bed?.room.number, bed: s.bed?.label,
          guardianName: s.guardianName, guardianPhone: s.guardianPhone,
          parentName: s.parentName, parentPhone: s.parentPhone,
          address: s.address, city: s.city, state: s.state, postalCode: s.postalCode,
          depositAmount: s.depositAmount, depositPaid: s.depositPaid, depositRefunded: s.depositRefunded,
          // The ID number is deliberately absent: an export is a file that
          // travels, and it does not need to carry Aadhaar numbers.
          kycIdType: s.kycIdType, kycStatus: s.kycStatus, policeVerificationStatus: s.policeVerificationStatus,
          joinedAt: s.createdAt,
        })),
      };
    }
    case 'rooms': {
      const rows = await db.room.findMany({
        include: { property: { select: { name: true } }, beds: { include: { student: { include: { user: { select: { name: true } } } } } } },
        orderBy: [{ floor: 'asc' }, { number: 'asc' }],
      });
      const employee = (await tenantKindOf(getTenantIdOrThrow())) === TenantKind.ENTERPRISE;
      return {
        columns: employee ? ['property', 'room', 'floor', 'type', 'bed', 'bedStatus', 'occupant', 'notes'] : ['property', 'room', 'floor', 'type', 'bed', 'bedStatus', 'bedRent', 'roomRent', 'occupant', 'notes'],
        rows: rows.flatMap((r) =>
          (r.beds.length ? r.beds : [null]).map((b) => ({
            property: r.property.name, room: r.number, floor: r.floor, type: r.type,
            bed: b?.label, bedStatus: b?.status, bedRent: b?.monthlyRent, roomRent: r.monthlyRent,
            occupant: b?.student?.user.name, notes: r.notes,
          })),
        ),
      };
    }
    case 'invoices': {
      const rows = await db.invoice.findMany({
        include: { student: { include: { user: { select: { name: true, email: true } } } }, payments: { where: { status: 'CLEARED' }, select: { amount: true } } },
        orderBy: [{ periodMonth: 'desc' }, { createdAt: 'asc' }],
      });
      return {
        columns: ['period', 'type', 'student', 'email', 'amount', 'paid', 'balance', 'status', 'dueDate', 'paidAt', 'createdAt'],
        rows: rows.map((i) => {
          const paid = i.payments.reduce((n, p) => n + p.amount, 0);
          return { period: i.periodMonth, type: i.type, student: i.student.user.name, email: i.student.user.email, amount: i.amount, paid, balance: i.amount - paid, status: i.status, dueDate: i.dueDate, paidAt: i.paidAt, createdAt: i.createdAt };
        }),
      };
    }
    case 'payments': {
      const rows = await db.payment.findMany({
        include: { invoice: { include: { student: { include: { user: { select: { name: true } } } } } } },
        orderBy: { paidAt: 'desc' },
      });
      return {
        columns: ['paidAt', 'student', 'invoicePeriod', 'invoiceType', 'amount', 'method', 'note'],
        rows: rows.map((p) => ({ paidAt: p.paidAt, student: p.invoice.student.user.name, invoicePeriod: p.invoice.periodMonth, invoiceType: p.invoice.type, amount: p.amount, method: p.method, note: p.note })),
      };
    }
    case 'expenses': {
      const rows = await db.expense.findMany({ include: { property: { select: { name: true } } }, orderBy: { date: 'desc' } });
      return {
        columns: ['date', 'category', 'amount', 'property', 'note'],
        rows: rows.map((e) => ({ date: e.date, category: e.category, amount: e.amount, property: e.property?.name, note: e.note })),
      };
    }
    case 'mess-stock': {
      const costs = await tenantHasFeature(getTenantIdOrThrow(), 'expenses');
      const rows = await db.messStockEntry.findMany({ include: { item: { select: { name: true, unit: true } } }, orderBy: { date: 'desc' } });
      return {
        columns: ['date', 'item', 'direction', 'reason', 'quantity', 'unit', ...(costs ? ['cost'] : []), 'note'],
        rows: rows.map((e) => ({ date: e.date, item: e.item.name, direction: e.direction, reason: e.reason, quantity: e.quantity / 100, unit: e.item.unit, cost: e.cost, note: e.note })),
      };
    }
    case 'complaints': {
      const rows = await db.messComplaint.findMany({
        include: { student: { include: { user: { select: { name: true } } } }, replies: { select: { id: true } } },
        orderBy: { createdAt: 'desc' },
      });
      return {
        columns: ['createdAt', 'student', 'category', 'subject', 'status', 'replies', 'resolvedAt'],
        rows: rows.map((c) => ({ createdAt: c.createdAt, student: c.student.user.name, category: c.category, subject: c.subject, status: c.status, replies: c.replies.length, resolvedAt: c.resolvedAt })),
      };
    }
  }
}

accountRouter.get(
  '/export/datasets',
  asyncHandler(async (_req: Request, res: Response) => {
    const money = await tenantHasFeature(getTenantIdOrThrow(), 'expenses');
    res.json({ datasets: DATASETS.filter((d) => money || !MONEY_DATASETS.includes(d)) });
  }),
);

/** Sprint 6: a month's books as Tally vouchers (XML for Tally Prime's import, or a ledger CSV). */
accountRouter.get(
  '/export/tally',
  requireFeature('expenses'),
  asyncHandler(async (req: Request, res: Response) => {
    const period = String(req.query.period ?? '');
    if (!isValidPeriod(period)) throw new BadRequestError('period (YYYY-MM) is required');
    const format = req.query.format === 'csv' ? 'csv' : 'xml';
    const book = await buildTally(period);
    if (req.query.preview === 'true') return res.json({ period, firm: book.firm, counts: book.counts, ledgers: book.ledgers.size, vouchers: book.vouchers.length });
    if (format === 'csv') {
      res.setHeader('Content-Type', 'text/csv; charset=utf-8');
      res.setHeader('Content-Disposition', `attachment; filename="hostelcare-tally-${period}.csv"`);
      return res.send(tallyCsv(book));
    }
    res.setHeader('Content-Type', 'application/xml; charset=utf-8');
    res.setHeader('Content-Disposition', `attachment; filename="hostelcare-tally-${period}.xml"`);
    res.send(tallyXml(book));
  }),
);

accountRouter.get(
  '/export/:dataset',
  asyncHandler(async (req: Request, res: Response) => {
    const name = z.enum(DATASETS).parse(req.params.dataset);
    if (MONEY_DATASETS.includes(name) && !(await tenantHasFeature(getTenantIdOrThrow(), 'expenses'))) {
      throw new ForbiddenError('This module is not switched on for your account', 'FEATURE_OFF');
    }
    const { rows, columns } = await buildDataset(name);
    const stamp = new Date().toISOString().slice(0, 10);
    res.setHeader('Content-Type', 'text/csv; charset=utf-8');
    res.setHeader('Content-Disposition', `attachment; filename="hostelcare-${name}-${stamp}.csv"`);
    res.send(toCsv(rows, columns));
  }),
);

// ── Deletion request ────────────────────────────────────────────────────────

const requestSchema = z.object({ reason: z.string().trim().max(500).optional() });

accountRouter.get(
  '/deletion-request',
  asyncHandler(async (_req: Request, res: Response) => {
    const tenantId = getTenantIdOrThrow();
    const request = await prismaUnscoped.accountDeletionRequest.findFirst({
      where: { tenantId, status: 'PENDING' },
      orderBy: { createdAt: 'desc' },
    });
    res.json({ request });
  }),
);

accountRouter.post(
  '/deletion-request',
  asyncHandler(async (req: Request, res: Response) => {
    const tenantId = getTenantIdOrThrow();
    const { reason } = requestSchema.parse(req.body);
    const open = await prismaUnscoped.accountDeletionRequest.findFirst({ where: { tenantId, status: 'PENDING' } });
    if (open) throw new ConflictError('A deletion request is already waiting for the platform team');
    const request = await prismaUnscoped.accountDeletionRequest.create({
      data: { tenantId, requestedById: req.user!.sub, reason },
    });
    res.status(201).json({ request });
  }),
);

/** Withdraw while it is still pending — after a decision there is nothing to withdraw. */
accountRouter.delete(
  '/deletion-request',
  asyncHandler(async (_req: Request, res: Response) => {
    const tenantId = getTenantIdOrThrow();
    const open = await prismaUnscoped.accountDeletionRequest.findFirst({ where: { tenantId, status: 'PENDING' } });
    if (!open) throw new NotFoundError('There is no pending deletion request to withdraw');
    if (!open.id) throw new BadRequestError('Malformed request');
    await prismaUnscoped.accountDeletionRequest.update({ where: { id: open.id }, data: { status: 'CANCELLED', resolvedAt: new Date() } });
    res.status(204).send();
  }),
);
