import { Router, Request, Response } from 'express';
import { z } from 'zod';
import { CrmPropertyType } from '@prisma/client';
import { asyncHandler } from '../../middleware/asyncHandler';
import { rateLimit } from '../../middleware/rateLimit';
import { ingestLead } from './crm-leads.service';

/**
 * POST /api/public/leads — the website's contact and demo-request forms
 * (Sprint L1). No session: it is on the open web, so it is rate limited per
 * network, only the HostelCare website's origins may call it from a browser
 * (CORS, set in app.ts), and a hidden "website" field traps form-filling
 * bots — a filled trap gets the same thank-you and saves nothing.
 *
 * The answer never says whether the person was already known.
 */

export const publicLeadRouter = Router();

const limiter = rateLimit({ windowMs: 10 * 60 * 1000, max: 8, name: 'public-leads' });

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

const leadSchema = z
  .object({
    name: z.string().trim().min(2, 'Enter your name').max(120).refine((v) => /\p{L}/u.test(v), 'Enter your name'),
    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'),
    email: z.union([z.string().trim().toLowerCase().email('Enter a valid email address').max(160), z.literal('')]).optional(),
    hostelName: str(160),
    /** STUDENT = "I'm looking for a room": kept, but not a sales lead. */
    type: z.enum(['HOSTEL', 'DORMITORY', 'PG', 'OTHER', 'STUDENT']).optional(),
    beds: z.preprocess((v) => (v === '' || v === null ? undefined : v), z.coerce.number().int().min(1, 'Beds must be at least 1').max(100_000).optional()),
    city: str(80),
    state: str(80),
    message: str(1000),
    form: z.enum(['contact', 'demo']).default('contact'),
    consent: z.preprocess((v) => v === true || v === 'true' || v === 'on' || v === '1', z.boolean()).default(false),
    page: str(300),
    utmSource: str(100),
    utmMedium: str(100),
    utmCampaign: str(100),
    /** The trap: a real visitor never sees this field. */
    website: z.string().max(500).optional(),
  })
  .strip();

publicLeadRouter.post(
  '/',
  limiter,
  asyncHandler(async (req: Request, res: Response) => {
    const b = leadSchema.parse(req.body ?? {});
    if (b.website && b.website.trim()) {
      res.status(201).json({ ok: true });
      return;
    }
    const meta: Record<string, string> = {};
    if (b.form) meta.form = b.form;
    if (b.page) meta.page = b.page;
    if (b.utmSource) meta.utmSource = b.utmSource;
    if (b.utmMedium) meta.utmMedium = b.utmMedium;
    if (b.utmCampaign) meta.utmCampaign = b.utmCampaign;
    await ingestLead({
      name: b.name,
      phone: b.phone,
      email: b.email || null,
      hostelName: b.hostelName ?? null,
      type: b.type && b.type !== 'STUDENT' ? (b.type as CrmPropertyType) : null,
      beds: b.beds ?? null,
      city: b.city ?? null,
      state: b.state ?? null,
      message: b.message ?? null,
      notFit: b.type === 'STUDENT',
      consent: b.consent,
      source: 'Website',
      via: b.form === 'demo' ? 'Website demo request' : 'Website contact form',
      meta,
    });
    res.status(201).json({ ok: true });
  }),
);
