import { Router, Request, Response } from 'express';
import { z } from 'zod';
import { asyncHandler } from '../../middleware/asyncHandler';
import { rateLimit } from '../../middleware/rateLimit';
import { INDIAN_STATES } from '../../lib/india';
import { setRefreshCookie } from '../auth/auth.controller';
import { resendTrialCode, startTrial, verifyTrial } from './trials.service';

/**
 * /api/public/trials — the app's "Start free trial" page (Sprint L2).
 *
 * No session: the owner has no account yet. The page is served from the app
 * itself, so the normal app CORS applies (it needs the refresh cookie on the
 * last step). Every step is rate limited per network; the code step also
 * counts wrong codes per signup. A filled hidden "website" field (a bot)
 * gets a believable answer and nothing is kept.
 *
 *   POST /             the form → a code is emailed → { signupId, emailHint, … }
 *   POST /:id/resend   a new code on the same signup
 *   POST /:id/verify   { code } → the hostel is created → { user, accessToken, trial }
 */

export const trialsRouter = Router();

const startLimiter = rateLimit({ windowMs: 10 * 60 * 1000, max: 6, name: 'trial-start' });
const codeLimiter = rateLimit({ windowMs: 10 * 60 * 1000, max: 30, name: 'trial-code' });

const opt = (max: number) =>
  z
    .string()
    .trim()
    .max(max)
    .optional()
    .transform((v) => (v ? v : undefined));

const startSchema = z
  .object({
    name: z.string().trim().min(2, 'Enter your name').max(120).refine((v) => /\p{L}/u.test(v), 'Enter your name'),
    email: z.string().trim().toLowerCase().email('Enter a valid email address').max(160),
    phone: z
      .string()
      .trim()
      .max(20)
      .refine((v) => {
        const d = v.replace(/\D/g, '');
        return d.length >= 10 && d.length <= 15;
      }, 'Enter a phone number with at least 10 digits'),
    password: z.string().min(8, 'Use at least 8 characters').max(200),
    hostelName: z.string().trim().min(2, 'Enter the name of your hostel').max(120),
    kind: z.enum(['HOSTEL', 'DORMITORY']),
    city: z.string().trim().min(2, 'Enter your city').max(80),
    state: z.preprocess((v) => (v === '' || v === null ? undefined : v), z.enum(INDIAN_STATES).optional()),
    rooms: z.coerce.number().int('Whole rooms').min(1, 'At least 1 room').max(200, 'Up to 200 rooms to start; add more later'),
    bedsPerRoom: z.coerce.number().int('Whole beds').min(1, 'At least 1 bed').max(20, 'Up to 20 beds a room'),
    consent: z.preprocess((v) => v === true || v === 'true' || v === 'on' || v === '1', z.boolean()).default(false),
    page: opt(300),
    utmSource: opt(100),
    utmMedium: opt(100),
    utmCampaign: opt(100),
    /** The trap: a real visitor never sees this field. */
    website: z.string().max(500).optional(),
  })
  .strip();

const idSchema = z.object({ id: z.string().uuid() });
const verifySchema = z.object({ code: z.string().trim().regex(/^\d{6}$/, 'Enter the 6-digit code') });

const ipOf = (req: Request) => (req.headers['x-forwarded-for']?.toString().split(',')[0] ?? req.ip ?? '').trim().slice(0, 64) || null;

trialsRouter.post(
  '/',
  startLimiter,
  asyncHandler(async (req: Request, res: Response) => {
    const { website, ...form } = startSchema.parse(req.body ?? {});
    if (website && website.trim()) {
      // Looks like success to a bot; no row, no email.
      res.status(201).json({ signupId: '00000000-0000-4000-8000-000000000000', emailHint: '•••', expiresInSeconds: 600, resendAfterSeconds: 30 });
      return;
    }
    res.status(201).json(await startTrial(form, ipOf(req)));
  }),
);

trialsRouter.post(
  '/:id/resend',
  codeLimiter,
  asyncHandler(async (req: Request, res: Response) => {
    const { id } = idSchema.parse(req.params);
    res.json(await resendTrialCode(id));
  }),
);

trialsRouter.post(
  '/:id/verify',
  codeLimiter,
  asyncHandler(async (req: Request, res: Response) => {
    const { id } = idSchema.parse(req.params);
    const { code } = verifySchema.parse(req.body ?? {});
    const { user, accessToken, refreshToken, trial } = await verifyTrial(id, code);
    setRefreshCookie(res, refreshToken);
    res.status(201).json({ user, accessToken, trial });
  }),
);
