import { Router, Request, Response } from 'express';
import { z } from 'zod';
import { Role } from '@prisma/client';
import { asyncHandler } from '../../middleware/asyncHandler';
import { authenticate } from '../../middleware/authenticate';
import { authorize } from '../../middleware/authorize';
import * as svc from './platform.service';
import { platformDashboard } from './dashboard.service';
import { planReminderOverview, runPlanReminders } from './plan-reminders.service';
import { env } from '../../config/env';
import { NotFoundError } from '../../lib/errors';

/** Platform settings are SUPER_ADMIN-only — they are not tenant data. */
export const platformRouter = Router();
platformRouter.use(authenticate, authorize(Role.SUPER_ADMIN));

/** Free text with a length cap and no control characters, trimmed. */
const text = (label: string, max: number) =>
  z
    .string()
    .trim()
    .max(max, `${label} must be at most ${max} characters`)
    .refine((v) => !/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/.test(v), `${label} contains invalid characters`);

const updateSchema = z
  .object({
    platformName: z.string().min(2).max(80),
    // Blank is allowed: these are optional contact details, not required ones.
    supportEmail: z.union([z.string().email().max(160), z.literal('')]),
    supportPhone: z.string().max(20),
    websiteUrl: z.union([z.string().url().max(200), z.literal('')]),
    /** 0 = last day of the month; otherwise clamp to a day every month has. */
    invoiceDueDay: z.coerce.number().int().min(0).max(28),

    // Billing profile: the operator's details printed as the seller on every
    // invoice to a hostel. All optional. GSTIN and PAN are upper-cased and
    // must be letters and digits of the right length; whether they match the
    // official pattern is a warning in the form, not a refusal, as in GymCare.
    billingCompanyName: text('Company / legal name', 100),
    billingEmail: z.union([z.string().trim().toLowerCase().email('Enter a valid email address').max(160), z.literal('')]),
    billingPhone: z.string().trim().max(20, 'Phone must be at most 20 characters').regex(/^[0-9+()\-\s]*$/, 'Phone can only have digits, spaces, +, - and brackets'),
    billingWebsite: z.union([z.string().trim().url('Enter a full web address, starting with https://').max(255), z.literal('')]),
    billingGstin: z.string().trim().toUpperCase().regex(/^([0-9A-Z]{15})?$/, 'A GST number is 15 letters and digits'),
    billingPan: z.string().trim().toUpperCase().regex(/^([0-9A-Z]{10})?$/, 'A PAN is 10 letters and digits'),
    billingAddress: text('Address', 255),
    billingCity: text('City', 100),
    billingState: text('State', 100),
    billingCountry: text('Country', 100),
    billingZip: z.string().trim().max(20, 'Zip / postal code must be at most 20 characters').regex(/^[0-9A-Za-z\-\s]*$/, 'Zip / postal code can only have letters, digits, spaces and -'),

    // Plan expiry reminders: on/off, the days before the paid-until date
    // (up to five, 0–60, kept largest first), and Monday's summary.
    planRemindersEnabled: z.boolean(),
    planReminderDays: z
      .array(z.number().int('Whole days').min(0, 'Between 0 and 60 days').max(60, 'Between 0 and 60 days'))
      .min(1, 'Pick at least one day')
      .max(5, 'At most five reminders')
      .transform((l) => [...new Set(l)].sort((a, b) => b - a)),
    planWeeklySummary: z.boolean(),
  })
  .partial()
  .refine((v) => Object.keys(v).length > 0, 'Nothing to update');

platformRouter.get(
  '/settings',
  asyncHandler(async (_req: Request, res: Response) => {
    res.json({ settings: await svc.getSettings() });
  }),
);

platformRouter.put(
  '/settings',
  asyncHandler(async (req: Request, res: Response) => {
    const input = updateSchema.parse(req.body);
    res.json({ settings: await svc.updateSettings(input) });
  }),
);

/** Plan expiry reminders: the settings, paid-until dates coming up, and what was sent. */
platformRouter.get(
  '/plan-reminders',
  asyncHandler(async (_req: Request, res: Response) => {
    res.json(await planReminderOverview());
  }),
);

/** The test clock: run the reminder pass as if it were `now`. Never in production. */
platformRouter.post(
  '/dev/plan-reminders',
  asyncHandler(async (req: Request, res: Response) => {
    if (!env.CRM_TEST_CLOCK || env.NODE_ENV === 'production') throw new NotFoundError('Not found');
    const { now } = z.object({ now: z.string().datetime({ offset: true }) }).parse(req.body);
    res.json({ result: await runPlanReminders(new Date(now)) });
  }),
);

/** The super admin's overview: revenue, hostels, platform usage, and what needs attention. */
platformRouter.get(
  '/dashboard',
  asyncHandler(async (_req: Request, res: Response) => {
    res.json({ dashboard: await platformDashboard() });
  }),
);

