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 { rateLimit } from '../../middleware/rateLimit';
import { actorOf, requireCrmAccess } from './crm-access';
import * as users from './crm-users.service';
import * as invites from './crm-invites.service';
import { defaultCopyEmail, getCrmSettings, updateCrmSettings } from './crm-settings.service';
import { crmRecordsRouter } from './crm-records.routes';
import { crmDealsRouter } from './crm-deals.routes';
import { env } from '../../config/env';
import { BadRequestError, NotFoundError } from '../../lib/errors';
import { assertMember } from './crm-contacts.service';
import { dashboard } from './crm-dashboard.service';
import { emailLog, getPrefs, setPrefs } from './crm-mail';
import { tick } from './crm-automation';
import { crmFollowUpsRouter } from './crm-followups';
import { crmAiRouter } from './crm-ai.routes';
import { crmDemosRouter } from './crm-demos.routes';
import { crmTouchRouter } from './crm-touch.routes';
import { crmNurtureRouter } from './crm-nurture.routes';
import { AI_FEATURES } from './crm-ai.service';

/**
 * The CRM: the platform's own sales workspace.
 *
 *   /api/crm/invites/:token      public — the set-password page behind an invite link
 *   /api/crm/workspace           SUPER_ADMIN + CRM_USER
 *   /api/crm/users, /settings    SUPER_ADMIN only
 *
 * No hostel role ever gets past requireCrmAccess.
 */
export const crmRouter = Router();

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

const email = z.string().trim().toLowerCase().email('Enter a valid email address').max(160, 'Email must be at most 160 characters');
const phone = z
  .string()
  .trim()
  .max(20, 'Phone must be at most 20 characters')
  .regex(/^[0-9+()\-\s]*$/, 'Phone can only have digits, spaces, +, - and brackets');

const createUserSchema = z.object({ name: text('Name', 2, 120), email, phone: phone.optional() });
const updateUserSchema = z
  .object({ name: text('Name', 2, 120), email, phone })
  .partial()
  .refine((v) => Object.keys(v).length > 0, 'Nothing to update');
const listQuery = z.object({
  search: z.string().trim().max(100).optional(),
  status: z.enum(['INVITED', 'ACTIVE', 'DEACTIVATED']).optional(),
});
const settingsSchema = z
  .object({
    emailsEnabled: z.boolean(),
    copySuperAdmin: z.boolean(),
    copyEmail: z.union([email, z.literal('')]),
    teamFollowUps: z.boolean(),
    aiEnabled: z.boolean(),
    aiFeatures: z.array(z.enum(AI_FEATURES)).max(AI_FEATURES.length).transform((l) => [...new Set(l)]),
    aiMonthlyBudgetUsd: z.number().min(0, 'The budget cannot be negative').max(10_000, 'At most US$10,000 a month'),
    // Lead routing (L1).
    leadOwnerId: z.string().uuid('Choose a team member').nullable(),
    leadOwnerOnLeave: z.boolean(),
    workDays: z
      .array(z.number().int().min(0).max(6))
      .min(1, 'Pick at least one working day')
      .max(7)
      .transform((l) => [...new Set(l)].sort()),
    workStart: z.string().regex(/^([01]\d|2[0-3]):[0-5]\d$/, 'Use a time like 10:00'),
    workEnd: z.string().regex(/^([01]\d|2[0-3]):[0-5]\d$/, 'Use a time like 19:00'),
    responseMinutes: z.number().int().min(5, 'At least 5 minutes').max(1440, 'At most 24 hours'),
    hotBeds: z.number().int().min(1, 'At least 1 bed').max(100_000),
    // Demo booking (L3).
    demoDailyCap: z.number().int().min(1, 'At least 1 demo a day').max(48, 'At most 48 a day'),
    demoMinutes: z.union([z.literal(15), z.literal(20), z.literal(30), z.literal(45), z.literal(60)], { errorMap: () => ({ message: 'Choose 15, 20, 30, 45 or 60 minutes' }) }),
    demoNoticeMinutes: z.number().int().min(0, 'Cannot be negative').max(10_080, 'At most a week'),
    demoDaysAhead: z.number().int().min(1, 'At least 1 day').max(60, 'At most 60 days'),
    // First touch (L4).
    autoFirstMessage: z.boolean(),
    waAutoReply: z.boolean(),
    // Trial journey (L5).
    requireNextStep: z.boolean(),
    trialNudges: z.boolean(),
    contactSources: z
      .array(text('Source', 1, 40))
      .min(1, 'Keep at least one source')
      .max(30, 'At most 30 sources')
      .transform((list) => list.filter((v, i) => list.findIndex((w) => w.toLowerCase() === v.toLowerCase()) === i)),
  })
  .partial()
  .refine((v) => Object.keys(v).length > 0, 'Nothing to update')
  .refine((v) => !v.workStart || !v.workEnd || v.workStart < v.workEnd, { message: 'The working day must end after it starts', path: ['workEnd'] });
const acceptSchema = z.object({
  password: z.string().min(8, 'Password must be at least 8 characters').max(200, 'Password must be at most 200 characters'),
});
const idParam = z.object({ id: z.string().uuid('Invalid id') });

// ── Public: the set-password page behind an invite or reset link ───────────

// A token is 256 random bits, but the page is on the open web: cap guessing.
const inviteLimiter = rateLimit({ windowMs: 15 * 60 * 1000, max: 30, name: 'crm-invite' });

crmRouter.get(
  '/invites/:token',
  inviteLimiter,
  asyncHandler(async (req: Request, res: Response) => {
    res.json({ invite: await invites.lookupInvite(String(req.params.token)) });
  }),
);

crmRouter.post(
  '/invites/:token/accept',
  inviteLimiter,
  asyncHandler(async (req: Request, res: Response) => {
    const { password } = acceptSchema.parse(req.body);
    res.json(await invites.acceptInvite(String(req.params.token), password));
  }),
);

// ── Everything below: signed in, platform team only ────────────────────────

crmRouter.use(authenticate, requireCrmAccess);

/** What every CRM screen needs to start: who I am and who I work with. */
crmRouter.get(
  '/workspace',
  asyncHandler(async (req: Request, res: Response) => {
    const settings = await getCrmSettings();
    res.json({
      me: { ...actorOf(res), role: req.user!.role },
      members: await users.crmMembers(),
      settings: { emailsEnabled: settings.emailsEnabled },
    });
  }),
);

// Contacts, lists, bin, import/export: the whole team.
crmRouter.use(crmRecordsRouter);
// Deals, pipeline stages and tasks.
crmRouter.use(crmDealsRouter);
// AI help.
crmRouter.use(crmAiRouter);
// Demo booking: hours, slots, booking during a call, outcomes (L3).
crmRouter.use(crmDemosRouter);
// Call outcomes, call-backs and the Meta lead log (L4).
crmRouter.use(crmTouchRouter);
// Opt-out, nurture, funnel and spend (L6).
crmRouter.use(crmNurtureRouter);
crmRouter.use(crmFollowUpsRouter);

/** The dashboard: my figures, or the team's. */
crmRouter.get(
  '/dashboard',
  asyncHandler(async (req: Request, res: Response) => {
    const { scope } = z.object({ scope: z.enum(['me', 'team']).default('team') }).parse(req.query);
    res.json({ dashboard: await dashboard(scope, actorOf(res).id) });
  }),
);

/** My own CRM email choices. */
const prefsSchema = z
  .object({
    alerts: z.boolean(),
    allActivity: z.boolean(),
    followUps: z.boolean(),
    tasks: z.boolean(),
    daily: z.boolean(),
    weekly: z.boolean(),
    summaryHour: z.number().int().min(6, 'Between 6 and 11 am').max(11, 'Between 6 and 11 am'),
  })
  .partial()
  .refine((v) => Object.keys(v).length > 0, 'Nothing to update');

crmRouter.get(
  '/notifications',
  asyncHandler(async (_req: Request, res: Response) => {
    res.json({ prefs: await getPrefs(actorOf(res).id) });
  }),
);
crmRouter.put(
  '/notifications',
  asyncHandler(async (req: Request, res: Response) => {
    res.json({ prefs: await setPrefs(actorOf(res).id, prefsSchema.parse(req.body)) });
  }),
);

/**
 * Test clock: run the CRM's scheduled work as if it were `now`. Exists only
 * where CRM_TEST_CLOCK is on, which the server refuses in production.
 */
crmRouter.post(
  '/dev/tick',
  authorize(Role.SUPER_ADMIN),
  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({ sent: await tick(new Date(now)) });
  }),
);

const superAdmin = authorize(Role.SUPER_ADMIN);

crmRouter.get(
  '/users',
  superAdmin,
  asyncHandler(async (req: Request, res: Response) => {
    res.json(await users.listCrmUsers(listQuery.parse(req.query)));
  }),
);

crmRouter.post(
  '/users',
  superAdmin,
  asyncHandler(async (req: Request, res: Response) => {
    const input = createUserSchema.parse(req.body);
    res.status(201).json(await users.createCrmUser(input, actorOf(res)));
  }),
);

crmRouter.patch(
  '/users/:id',
  superAdmin,
  asyncHandler(async (req: Request, res: Response) => {
    const { id } = idParam.parse(req.params);
    res.json({ user: await users.updateCrmUser(id, updateUserSchema.parse(req.body), actorOf(res)) });
  }),
);

crmRouter.post(
  '/users/:id/password-link',
  superAdmin,
  asyncHandler(async (req: Request, res: Response) => {
    const { id } = idParam.parse(req.params);
    res.json(await users.sendPasswordLink(id, actorOf(res)));
  }),
);

crmRouter.post(
  '/users/:id/deactivate',
  superAdmin,
  asyncHandler(async (req: Request, res: Response) => {
    const { id } = idParam.parse(req.params);
    res.json({ user: await users.deactivateCrmUser(id, actorOf(res)) });
  }),
);

crmRouter.post(
  '/users/:id/reactivate',
  superAdmin,
  asyncHandler(async (req: Request, res: Response) => {
    const { id } = idParam.parse(req.params);
    res.json({ user: await users.reactivateCrmUser(id, actorOf(res)) });
  }),
);

crmRouter.post(
  '/users/:id/sign-out',
  superAdmin,
  asyncHandler(async (req: Request, res: Response) => {
    const { id } = idParam.parse(req.params);
    res.json({ user: await users.signOutEverywhere(id) });
  }),
);

/** The CRM's recent email, for the super admin to see what went out. */
crmRouter.get(
  '/email-log',
  superAdmin,
  asyncHandler(async (req: Request, res: Response) => {
    const q = z.object({ limit: z.coerce.number().int().min(1).max(200).default(50), kind: z.string().max(30).optional() }).parse(req.query);
    res.json({ emails: await emailLog(q.limit, q.kind) });
  }),
);

crmRouter.get(
  '/settings',
  superAdmin,
  asyncHandler(async (_req: Request, res: Response) => {
    res.json({ settings: await getCrmSettings(), defaultCopyEmail: await defaultCopyEmail() });
  }),
);

crmRouter.put(
  '/settings',
  superAdmin,
  asyncHandler(async (req: Request, res: Response) => {
    const input = settingsSchema.parse(req.body);
    // The lead owner must be someone on the CRM team.
    if (input.leadOwnerId) await assertMember(input.leadOwnerId);
    // Start and end are checked together against what is stored.
    if (input.workStart || input.workEnd) {
      const now = await getCrmSettings();
      if ((input.workStart ?? now.workStart) >= (input.workEnd ?? now.workEnd)) throw new BadRequestError('The working day must end after it starts');
    }
    res.json({ settings: await updateCrmSettings(input), defaultCopyEmail: await defaultCopyEmail() });
  }),
);
