import { Router, Request, Response } from 'express';
import { z } from 'zod';
import { ChargeFrequency, LateFeeMode } from '@prisma/client';
import { asyncHandler } from '../../middleware/asyncHandler';
import { authenticate } from '../../middleware/authenticate';
import { requireFeature } from '../../middleware/requireFeature';
import { requirePermission } from '../../middleware/requirePermission';
import { getTenantIdOrThrow } from '../../lib/tenantContext';
import * as rules from './billing-rules.service';

/**
 * Billing rules and the charge catalogue, per property.
 *
 * Mounted under /api/properties beside the property router, but guarded by
 * MANAGE_RENT rather than MANAGE_ROOMS: these decide what students are
 * charged, which is the rent clerk's call, not the warden's. Every path
 * names the property, and the scoped client makes another tenant's property
 * a 404.
 */
export const billingRulesRouter = Router();
// Per route, not router.use(): this router shares its mount with the property
// router, and a router-level guard would 403 every property request that
// merely passed through on its way there.
const guard = [authenticate, requireFeature('billing'), requirePermission('MANAGE_RENT')] as const;

const rulesSchema = z
  .object({
    prorataEnabled: z.boolean(),
    lateFeeEnabled: z.boolean(),
    lateFeeGraceDays: z.number().int().min(0).max(60),
    lateFeeMode: z.nativeEnum(LateFeeMode),
    lateFeeAmount: z.number().int().min(0).max(100000),
    lateFeeCap: z.number().int().min(0).max(1000000).nullable(),
    gstEnabled: z.boolean(),
    gstRate: z.number().int().min(0).max(28),
    gstThreshold: z.number().int().min(0).max(1000000),
    gstInclusive: z.boolean(),
  })
  .partial()
  .refine((v) => Object.keys(v).length > 0, 'Nothing to update');

billingRulesRouter.get(
  '/:id/billing-rules',
  ...guard,
  asyncHandler(async (req: Request, res: Response) => {
    res.json({ rules: await rules.getBillingRules(req.params.id) });
  }),
);

billingRulesRouter.put(
  '/:id/billing-rules',
  ...guard,
  asyncHandler(async (req: Request, res: Response) => {
    const input = rulesSchema.parse(req.body);
    res.json({ rules: await rules.updateBillingRules(req.params.id, input) });
  }),
);

/** The hourly late-fee pass, on demand — after turning the rule on, or to see it work. */
billingRulesRouter.post(
  '/:id/billing-rules/run-late-fees',
  ...guard,
  asyncHandler(async (req: Request, res: Response) => {
    await rules.getBillingRules(req.params.id); // 404 for a property outside the tenant
    res.json({ result: await rules.applyLateFees(getTenantIdOrThrow()) });
  }),
);

// ── Charge catalogue ───────────────────────────────────────────────────────

const chargeTypeSchema = z.object({
  name: z.string().trim().min(2).max(60),
  amount: z.number().int().min(1).max(1000000),
  frequency: z.nativeEnum(ChargeFrequency),
  appliesToAll: z.boolean().optional(),
  active: z.boolean().optional(),
});

billingRulesRouter.get(
  '/:id/charge-types',
  ...guard,
  asyncHandler(async (req: Request, res: Response) => {
    res.json({ chargeTypes: await rules.listChargeTypes(req.params.id) });
  }),
);

billingRulesRouter.post(
  '/:id/charge-types',
  ...guard,
  asyncHandler(async (req: Request, res: Response) => {
    const input = chargeTypeSchema.parse(req.body);
    res.status(201).json({ chargeType: await rules.createChargeType(req.params.id, input) });
  }),
);

billingRulesRouter.patch(
  '/:id/charge-types/:chargeTypeId',
  ...guard,
  asyncHandler(async (req: Request, res: Response) => {
    const input = chargeTypeSchema.partial().refine((v) => Object.keys(v).length > 0, 'Nothing to update').parse(req.body);
    res.json({ chargeType: await rules.updateChargeType(req.params.chargeTypeId, input) });
  }),
);

billingRulesRouter.delete(
  '/:id/charge-types/:chargeTypeId',
  ...guard,
  asyncHandler(async (req: Request, res: Response) => {
    res.json(await rules.deleteChargeType(req.params.chargeTypeId));
  }),
);

/** Which students a selective charge applies to; replaces the whole set. */
billingRulesRouter.put(
  '/:id/charge-types/:chargeTypeId/students',
  ...guard,
  asyncHandler(async (req: Request, res: Response) => {
    const { studentIds } = z.object({ studentIds: z.array(z.string().uuid()).max(2000) }).parse(req.body);
    res.json({ chargeType: await rules.setChargeStudents(req.params.chargeTypeId, studentIds) });
  }),
);
