import { Router, Request, Response } from 'express';
import { z } from 'zod';
import { CrmDemoLanguage, CrmDemoStatus, CrmPropertyType, Role } from '@prisma/client';
import { asyncHandler } from '../../middleware/asyncHandler';
import { ForbiddenError } from '../../lib/errors';
import { env } from '../../config/env';
import { rateLimit } from '../../middleware/rateLimit';
import { actorOf } from './crm-access';
import { assertMember } from './crm-contacts.service';
import * as demos from './crm-demos.service';

/**
 * Demo booking (Sprint L3).
 *
 * publicDemoRouter — /api/public/demos, for the website's booking page. No
 * session: rate limited per network, the website's origins only (CORS in
 * app.ts), a honeypot on the form. The owner's private link (a token) is
 * the only way to see, move or cancel a booking; it never reveals the host's
 * email or anything else in the CRM.
 *
 * crmDemosRouter — /api/crm/…, behind requireCrmAccess: demo hours, the
 * slot list, booking for a contact during a call, moving, cancelling, and
 * the Done / No-show outcomes. Every CRM member; another member's hours are
 * the super admin's.
 */

export const publicDemoRouter = Router();

const slotsLimiter = rateLimit({ windowMs: 10 * 60 * 1000, max: 120, name: 'demo-slots' });
const bookLimiter = rateLimit({ windowMs: 10 * 60 * 1000, max: 8, name: 'demo-book' });
const manageLimiter = rateLimit({ windowMs: 10 * 60 * 1000, max: 40, name: 'demo-manage' });

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

const slot = z.string().datetime({ offset: true, message: 'Pick a time' });

const bookSchema = z
  .object({
    slot,
    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: opt(160),
    type: z.enum(['HOSTEL', 'DORMITORY', 'PG', 'OTHER']).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: opt(80),
    language: z.enum(['EN', 'HI']).default('EN'),
    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 tokenParam = z.object({ token: z.string().min(20).max(100).regex(/^[A-Za-z0-9_-]+$/, 'Invalid link') });

publicDemoRouter.get(
  '/slots',
  slotsLimiter,
  asyncHandler(async (_req: Request, res: Response) => {
    res.set('Cache-Control', 'no-store');
    res.json(await demos.publicSlots());
  }),
);

publicDemoRouter.post(
  '/',
  bookLimiter,
  asyncHandler(async (req: Request, res: Response) => {
    const b = bookSchema.parse(req.body ?? {});
    if (b.website && b.website.trim()) {
      // A bot: a believable answer, nothing booked.
      res.status(201).json({ demo: null, manageToken: null });
      return;
    }
    const meta: Record<string, string> = {};
    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;
    const r = await demos.bookDemo(
      {
        slot: new Date(b.slot),
        language: b.language as CrmDemoLanguage,
        consent: b.consent,
        lead: {
          name: b.name,
          phone: b.phone,
          email: b.email || null,
          hostelName: b.hostelName ?? null,
          type: (b.type as CrmPropertyType | undefined) ?? null,
          beds: b.beds ?? null,
          city: b.city ?? null,
          consent: b.consent,
          message: `Booked a demo for ${demos.fmtWhen(new Date(b.slot))}${b.language === 'HI' ? ' (Hindi)' : ''}.`,
          meta,
        },
      },
      { via: 'website' },
    );
    res.status(201).json({ demo: demos.publicView(r.demo), manageToken: r.token });
  }),
);

publicDemoRouter.get(
  '/manage/:token',
  manageLimiter,
  asyncHandler(async (req: Request, res: Response) => {
    const { token } = tokenParam.parse(req.params);
    res.set('Cache-Control', 'no-store');
    res.json({ demo: await demos.viewByToken(token) });
  }),
);

publicDemoRouter.get(
  '/manage/:token/ics',
  manageLimiter,
  asyncHandler(async (req: Request, res: Response) => {
    const { token } = tokenParam.parse(req.params);
    res.set('Content-Type', 'text/calendar; charset=utf-8');
    res.set('Content-Disposition', 'attachment; filename="hostelcare-demo.ics"');
    res.send(await demos.icsByToken(token));
  }),
);

publicDemoRouter.post(
  '/manage/:token/reschedule',
  manageLimiter,
  asyncHandler(async (req: Request, res: Response) => {
    const { token } = tokenParam.parse(req.params);
    const b = z.object({ slot }).parse(req.body ?? {});
    res.json({ demo: await demos.rescheduleByToken(token, b.slot) });
  }),
);

publicDemoRouter.post(
  '/manage/:token/cancel',
  manageLimiter,
  asyncHandler(async (req: Request, res: Response) => {
    const { token } = tokenParam.parse(req.params);
    const b = z.object({ reason: opt(300) }).parse(req.body ?? {});
    res.json({ demo: await demos.cancelByToken(token, b.reason ?? null) });
  }),
);

// ── CRM ────────────────────────────────────────────────────────────────────

export const crmDemosRouter = Router();

const hhmm = z.string().regex(/^([01]\d|2[0-3]):[0-5]\d$/, 'Use a time like 10:00');
const hoursSchema = z
  .object({
    enabled: z.boolean(),
    meetUrl: z.union([z.string().trim().url('Paste the full Meet link, starting https://').max(300).refine((v) => v.startsWith('https://'), 'The link must start with https://'), z.literal(''), z.null()]),
    hours: z
      .array(z.object({ day: z.number().int().min(0).max(6), start: hhmm, end: hhmm }).refine((r) => r.start < r.end, { message: 'Each range must end after it starts', path: ['end'] }))
      .max(42, 'At most 42 time ranges'),
  })
  .partial()
  .refine((v) => Object.keys(v).length > 0, 'Nothing to update');
const blockSchema = z.object({
  startsAt: z.string().datetime({ offset: true }),
  endsAt: z.string().datetime({ offset: true }),
  note: z.string().trim().max(200).optional().nullable(),
});
const idParam = z.object({ id: z.string().uuid('Invalid id') });
/**
 * Test clock for outcomes, like /dev/tick: honoured only where CRM_TEST_CLOCK
 * is on (refused in production), so the suite can record how a future demo went.
 */
const testAt = z.string().datetime({ offset: true }).optional();
const clock = (at?: string) => (at && env.CRM_TEST_CLOCK && env.NODE_ENV !== 'production' ? new Date(at) : new Date());
const whoParam = z.object({ userId: z.union([z.literal('me'), z.string().uuid('Invalid id')]) });

/** "me", or another member's hours — those are the super admin's to change. */
async function whose(req: Request, res: Response) {
  const { userId } = whoParam.parse(req.params);
  if (userId === 'me' || userId === actorOf(res).id) return actorOf(res).id;
  if (req.user!.role !== Role.SUPER_ADMIN) throw new ForbiddenError("Only the super admin can change someone else's demo hours.");
  await assertMember(userId);
  return userId;
}

crmDemosRouter.get(
  '/demo-hours/:userId',
  asyncHandler(async (req: Request, res: Response) => {
    res.json({ hours: await demos.getDemoHours(await whose(req, res)) });
  }),
);

crmDemosRouter.put(
  '/demo-hours/:userId',
  asyncHandler(async (req: Request, res: Response) => {
    const userId = await whose(req, res);
    const b = hoursSchema.parse(req.body ?? {});
    res.json({ hours: await demos.setDemoHours(userId, { ...b, meetUrl: b.meetUrl === '' ? null : b.meetUrl }) });
  }),
);

crmDemosRouter.post(
  '/demo-hours/:userId/blocks',
  asyncHandler(async (req: Request, res: Response) => {
    const userId = await whose(req, res);
    const b = blockSchema.parse(req.body ?? {});
    res.status(201).json({ hours: await demos.addDemoBlock(userId, { startsAt: new Date(b.startsAt), endsAt: new Date(b.endsAt), note: b.note }) });
  }),
);

crmDemosRouter.delete(
  '/demo-hours/:userId/blocks/:id',
  asyncHandler(async (req: Request, res: Response) => {
    const userId = await whose(req, res);
    const { id } = idParam.parse({ id: req.params.id });
    res.json({ hours: await demos.removeDemoBlock(userId, id) });
  }),
);

crmDemosRouter.get(
  '/demos/slots',
  asyncHandler(async (req: Request, res: Response) => {
    const q = z.object({ hostId: z.string().uuid().optional(), days: z.coerce.number().int().min(1).max(31).optional() }).parse(req.query);
    res.json(await demos.crmSlots(q));
  }),
);

const listQuery = z.object({
  from: z.string().datetime({ offset: true }).optional(),
  to: z.string().datetime({ offset: true }).optional(),
  hostId: z.string().uuid().optional(),
  contactId: z.string().uuid().optional(),
  status: z.nativeEnum(CrmDemoStatus).optional(),
  limit: z.coerce.number().int().min(1).max(200).default(100),
});

crmDemosRouter.get(
  '/demos',
  asyncHandler(async (req: Request, res: Response) => {
    const q = listQuery.parse(req.query);
    res.json({ demos: await demos.listDemos({ from: q.from ? new Date(q.from) : undefined, to: q.to ? new Date(q.to) : undefined, hostId: q.hostId, contactId: q.contactId, status: q.status }, q.limit) });
  }),
);

crmDemosRouter.post(
  '/demos',
  asyncHandler(async (req: Request, res: Response) => {
    const b = z.object({ contactId: z.string().uuid(), slot, hostId: z.string().uuid().optional(), language: z.enum(['EN', 'HI']).default('EN') }).parse(req.body ?? {});
    res.status(201).json({ demo: await demos.bookFromCrm({ ...b, language: b.language as CrmDemoLanguage }, actorOf(res)) });
  }),
);

crmDemosRouter.get(
  '/demos/:id',
  asyncHandler(async (req: Request, res: Response) => {
    res.json({ demo: await demos.getDemo(idParam.parse(req.params).id) });
  }),
);

crmDemosRouter.post(
  '/demos/:id/reschedule',
  asyncHandler(async (req: Request, res: Response) => {
    const { id } = idParam.parse(req.params);
    const b = z.object({ slot, hostId: z.string().uuid().optional() }).parse(req.body ?? {});
    res.json({ demo: await demos.moveFromCrm(id, b.slot, b.hostId, actorOf(res)) });
  }),
);

crmDemosRouter.post(
  '/demos/:id/cancel',
  asyncHandler(async (req: Request, res: Response) => {
    const { id } = idParam.parse(req.params);
    const b = z.object({ reason: opt(300) }).parse(req.body ?? {});
    res.json({ demo: await demos.cancelFromCrm(id, b.reason ?? null, actorOf(res)) });
  }),
);

crmDemosRouter.post(
  '/demos/:id/done',
  asyncHandler(async (req: Request, res: Response) => {
    const { id } = idParam.parse(req.params);
    const b = z.object({ note: opt(2000), at: testAt }).parse(req.body ?? {});
    res.json({ demo: await demos.markDemoDone(id, b.note ?? null, actorOf(res), clock(b.at)) });
  }),
);

crmDemosRouter.post(
  '/demos/:id/no-show',
  asyncHandler(async (req: Request, res: Response) => {
    const { id } = idParam.parse(req.params);
    const b = z.object({ at: testAt }).parse(req.body ?? {});
    res.json(await demos.markDemoNoShow(id, actorOf(res), clock(b.at)));
  }),
);
