import { Router, Request, Response } from 'express';
import { z } from 'zod';
import { asyncHandler } from '../../middleware/asyncHandler';
import { authenticate } from '../../middleware/authenticate';
import { requireFeature } from '../../middleware/requireFeature';
import { requirePermission } from '../../middleware/requirePermission';
import { presignDownload } from '../uploads/uploads.service';
import { db } from '../../lib/prisma';
import { ForbiddenError } from '../../lib/errors';
import { getTenantIdOrThrow } from '../../lib/tenantContext';
import { runRemindersForTenant } from './reminder-engine';
import { recentNotifications } from '../notifications/notifications.service';
import { FeeBearer, PaymentAccountStatus } from '@prisma/client';
import { BadRequestError } from '../../lib/errors';
import { env } from '../../config/env';
import { isRazorpayConfigured } from '../../lib/razorpay';
import { getPaymentSetup, refreshPaymentAccount, setupPaymentAccount } from '../payments/payment-account.service';

/**
 * The tenant's billing identity and reminder policy.
 *
 * Both live on TenantSettings next to the mess fee, but they are MANAGE_RENT
 * concerns — what the invoice document says, and when students get nudged —
 * so they get their own routes rather than widening the mess ones.
 */

const updateSchema = z.object({
  remindersEnabled: z.boolean().optional(),
  // Up to three offsets, most hostels use something like [15, 10, 1].
  reminderDaysBefore: z.array(z.coerce.number().int().min(0).max(60)).max(3).optional(),
  billingFirmName: z.string().max(120).nullable().optional(),
  // 15 chars, state code + PAN + entity + Z + checksum. Uppercased before the
  // pattern so a lowercase paste is corrected rather than rejected.
  billingGstin: z
    .string()
    .transform((v) => v.toUpperCase())
    .pipe(z.string().regex(/^\d{2}[A-Z]{5}\d{4}[A-Z][A-Z\d]Z[A-Z\d]$/, 'That is not a valid GSTIN'))
    .nullable()
    .optional(),
  billingAddress: z.string().max(300).nullable().optional(),
  billingPhone: z.string().min(7).max(20).nullable().optional(),
  billingEmail: z.string().email().nullable().optional(),
  billingLogoUrl: z.string().max(500).nullable().optional(),
  notifyPaymentEmail: z.boolean().optional(),
  notifyInvoiceEmail: z.boolean().optional(),
  notifyNoticeEmail: z.boolean().optional(),
  // Online collection (Sprint 2). Switching on needs a working gateway and,
  // when Route is required, an active linked account — checked below.
  onlineCollectionEnabled: z.boolean().optional(),
  feeBearer: z.nativeEnum(FeeBearer).optional(),
  virtualAccountsEnabled: z.boolean().optional(),
  billingAccentColor: z
    .string()
    .regex(/^#[0-9a-fA-F]{6}$/, 'Colour must be a hex value like #2563eb')
    .nullable()
    .optional(),
});

const PUBLIC_FIELDS = {
  remindersEnabled: true,
  reminderDaysBefore: true,
  notifyPaymentEmail: true,
  notifyInvoiceEmail: true,
  notifyNoticeEmail: true,
  onlineCollectionEnabled: true,
  feeBearer: true,
  virtualAccountsEnabled: true,
  billingFirmName: true,
  billingGstin: true,
  billingAddress: true,
  billingPhone: true,
  billingEmail: true,
  billingLogoUrl: true,
  billingAccentColor: true,
} as const;

export const billingSettingsRouter = Router();

// The firm identity on an invoice is for whoever reads the invoice — a
// student printing their receipt needs the name and GSTIN on it too. No
// reminder settings here, and the logo comes as a resolved read URL because
// students cannot mint one themselves.
billingSettingsRouter.get(
  '/public',
  authenticate,
  asyncHandler(async (req: Request, res: Response) => {
    if (!req.user!.tenantId) throw new ForbiddenError('Platform accounts have no hostel identity');
    const s = await db.tenantSettings.findFirst({
      select: { billingFirmName: true, billingGstin: true, billingAddress: true, billingPhone: true, billingEmail: true, billingLogoUrl: true, billingAccentColor: true },
    });
    let logoUrl: string | null = null;
    if (s?.billingLogoUrl) {
      logoUrl = await presignDownload(getTenantIdOrThrow(), s.billingLogoUrl).catch(() => null);
    }
    res.json({ identity: { ...(s ?? {}), logoUrl } });
  }),
);

billingSettingsRouter.use(authenticate, requirePermission('MANAGE_RENT'));

billingSettingsRouter.get(
  '/',
  asyncHandler(async (_req: Request, res: Response) => {
    const tenantId = getTenantIdOrThrow();
    const settings = await db.tenantSettings.findFirst({ select: PUBLIC_FIELDS });
    res.json({
      settings:
        settings ??
        (await db.tenantSettings.create({ data: { tenantId }, select: PUBLIC_FIELDS })),
    });
  }),
);

billingSettingsRouter.put(
  '/',
  asyncHandler(async (req: Request, res: Response) => {
    const tenantId = getTenantIdOrThrow();
    const input = updateSchema.parse(req.body);
    if (input.onlineCollectionEnabled) {
      if (!isRazorpayConfigured()) throw new BadRequestError('Online payments are not configured on this server yet', 'GATEWAY_NOT_CONFIGURED');
      if (env.RAZORPAY_ROUTE_REQUIRED) {
        const account = await db.hostelPaymentAccount.findFirst({ select: { productStatus: true, razorpayAccountId: true } });
        if (!account?.razorpayAccountId || account.productStatus !== PaymentAccountStatus.ACTIVE) {
          throw new BadRequestError('Connect and activate the hostel’s bank account before switching online payments on', 'PAYMENT_ACCOUNT_NOT_ACTIVE');
        }
      }
    }
    const existing = await db.tenantSettings.findFirst({});
    const settings = existing
      ? await db.tenantSettings.update({ where: { id: existing.id }, data: input, select: PUBLIC_FIELDS })
      : await db.tenantSettings.create({ data: { tenantId, ...input }, select: PUBLIC_FIELDS });
    res.json({ settings });
  }),
);

/**
 * Run this tenant's reminder pass right now.
 *
 * The scheduler ticks hourly anyway; this exists so an admin can see the
 * policy work the moment they set it up, instead of trusting a cron they
 * cannot observe. The ReminderLog makes it safe to press twice.
 */
billingSettingsRouter.post(
  '/reminders/run',
  requireFeature('billing'),
  asyncHandler(async (_req: Request, res: Response) => {
    res.json({ result: await runRemindersForTenant(getTenantIdOrThrow()) });
  }),
);

/** The last emails this hostel sent automatically, and whether each went. */
billingSettingsRouter.get(
  '/notifications/recent',
  asyncHandler(async (req: Request, res: Response) => {
    const limit = Number(req.query.limit) || 50;
    res.json({ notifications: await recentNotifications(getTenantIdOrThrow(), limit) });
  }),
);

// ── Online collection: the hostel's Razorpay Route account ──────────────────

const accountSchema = z.object({
  legalName: z.string().trim().min(2).max(120),
  businessType: z.enum(['individual', 'proprietorship', 'partnership', 'private_limited', 'llp', 'trust', 'society', 'ngo', 'public_limited']).default('individual'),
  contactName: z.string().trim().min(2).max(120),
  email: z.string().email(),
  phone: z.string().trim().min(10).max(15),
  addressLine: z.string().trim().min(3).max(200),
  city: z.string().trim().min(2).max(80),
  state: z.string().trim().min(2).max(80),
  postalCode: z.string().regex(/^\d{6}$/, 'Postal code must be 6 digits'),
  beneficiaryName: z.string().trim().min(2).max(120),
  accountNumber: z.string().regex(/^\d{9,18}$/, 'Account number must be 9 to 18 digits').optional(),
  ifsc: z.string().trim().toUpperCase().regex(/^[A-Z]{4}0[A-Z0-9]{6}$/, 'That is not a valid IFSC'),
  pan: z.string().trim().toUpperCase().regex(/^[A-Z]{5}\d{4}[A-Z]$/, 'That is not a valid PAN').optional(),
});

billingSettingsRouter.get(
  '/payments-account',
  requireFeature('onlinePayments'),
  asyncHandler(async (_req: Request, res: Response) => {
    res.json(await getPaymentSetup());
  }),
);

billingSettingsRouter.post(
  '/payments-account',
  requireFeature('onlinePayments'),
  asyncHandler(async (req: Request, res: Response) => {
    const input = accountSchema.parse(req.body);
    res.json({ account: await setupPaymentAccount(input) });
  }),
);

billingSettingsRouter.post(
  '/payments-account/refresh',
  requireFeature('onlinePayments'),
  asyncHandler(async (_req: Request, res: Response) => {
    res.json({ account: await refreshPaymentAccount() });
  }),
);
