import { Router, Request, Response } from 'express';
import { z } from 'zod';
import { asyncHandler } from '../../middleware/asyncHandler';
import { actorOf } from './crm-access';
import { assertStepUp, requireStepUp, resendStepUp, startStepUp, verifyStepUp, verifyStepUpTotp } from './crm-step-up';
import * as contacts from './crm-contacts.service';
import * as lists from './crm-lists.service';
import { IMPORT_FIELDS, exportContacts, importContacts } from './crm-import-export.service';

/**
 * CRM records: contacts, lists, the bin, import and export, and the step-up
 * code that guards the risky ones. Mounted on crmRouter after
 * requireCrmAccess, so the super admin and CRM users only — one shared
 * workspace, so no per-member filtering here.
 */
export const crmRecordsRouter = Router();

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

/** Optional text: '' or null clears it. */
const opt = (label: string, max: number, multiline = false) =>
  z.union([text(label, max, multiline), z.null()]).optional().transform((v) => (v === '' ? null : v));

const phone = (label: string) =>
  z
    .union([
      z
        .string()
        .trim()
        .max(20, `${label} must be at most 20 characters`)
        .regex(/^[0-9+()\-\s.]*$/, `${label} can only have digits, spaces, +, - and brackets`)
        .refine((v) => !v || (v.replace(/\D/g, '').length >= 7 && v.replace(/\D/g, '').length <= 15), `${label} needs 7 to 15 digits`),
      z.null(),
    ])
    .optional()
    .transform((v) => (v === '' ? null : v));

/** A person's name: letters in any script, spaces, dots, apostrophes and hyphens. */
const NAME = /^[\p{L}\p{M}][\p{L}\p{M}\s.'’-]*$/u;
const nameOpt = (label: string) =>
  opt(label, 80).refine((v) => !v || NAME.test(v), `${label} can only have letters, spaces, dots, apostrophes and hyphens`);
/** example.com, www.example.com/path or https://… — a domain with a dot. */
const WEB = /^(https?:\/\/)?([\w-]+\.)+[a-z]{2,}(:\d+)?(\/\S*)?$/i;

const dateOrNull = z
  .union([z.string().datetime({ offset: true, message: 'Enter a valid date and time' }), z.null()])
  .optional()
  .transform((v) => (v === undefined ? undefined : v === null ? null : new Date(v)));

const contactFields = {
  firstName: text('First name', 80)
    .pipe(z.string().min(1, 'First name is required'))
    .refine((v) => NAME.test(v), 'First name can only have letters, spaces, dots, apostrophes and hyphens'),
  lastName: nameOpt('Last name'),
  email: z
    .union([z.string().trim().toLowerCase().email('Enter a valid email address').max(160, 'Email must be at most 160 characters'), z.literal(''), z.null()])
    .optional()
    .transform((v) => (v === '' ? null : v)),
  phone: phone('Phone'),
  whatsapp: phone('WhatsApp'),
  designation: opt('Designation', 120),
  companyName: opt('Company', 160),
  website: opt('Website', 255).refine((v) => !v || WEB.test(v), 'Enter a web address like example.com'),
  linkedinUrl: opt('LinkedIn', 255).refine((v) => !v || /^(https?:\/\/)?([\w-]+\.)?linkedin\.com\/\S+$/i.test(v), 'Enter a LinkedIn link like linkedin.com/in/name'),
  city: opt('City', 80).refine((v) => !v || /^[\p{L}\p{M}][\p{L}\p{M}\s.()'-]*$/u.test(v), 'City can only have letters, spaces, dots and hyphens'),
  state: opt('State', 80),
  country: opt('Country', 80),
  address: opt('Address', 500, true),
  propertyType: z.enum(contacts.PROPERTY_TYPES as [string, ...string[]]).nullable().optional(),
  approxBeds: z.number().int('Beds must be a whole number').min(1, 'Beds must be at least 1').max(100_000, 'Beds must be at most 1,00,000').nullable().optional(),
  status: z.enum(contacts.CONTACT_STATUSES as [string, ...string[]]).optional(),
  source: opt('Source', 60),
  tags: z.array(text('Tag', 40)).max(20, 'At most 20 tags').optional(),
  about: opt('About', 2000, true),
  ownerId: z.string().uuid('Invalid owner').nullable().optional(),
  lastContactedAt: dateOrNull,
  nextFollowUpAt: dateOrNull,
};

const createSchema = z.object(contactFields);
const updateSchema = z
  .object(contactFields)
  .partial()
  .refine((v) => Object.values(v).some((x) => x !== undefined), 'Nothing to update');

const conditionSchema = z.object({
  field: z.enum(contacts.CONDITION_FIELDS),
  op: z.enum(contacts.CONDITION_OPS),
  value: z.unknown().optional(),
});

const querySchema = z.object({
  q: z.string().trim().max(200).optional(),
  status: z.array(z.enum(contacts.CONTACT_STATUSES as [string, ...string[]])).max(5).optional(),
  ownerId: z.union([z.string().uuid(), z.literal('none')]).optional(),
  source: z.string().trim().max(60).optional(),
  propertyType: z.enum(contacts.PROPERTY_TYPES as [string, ...string[]]).optional(),
  tag: z.string().trim().max(40).optional(),
  listId: z.string().uuid().optional(),
  followUp: z.enum(['overdue', 'today', 'week', 'none']).optional(),
  waiting: z.boolean().optional(),
  grade: z.enum(['HOT', 'WARM', 'PG', 'NOT_A_FIT']).optional(),
  conditions: z.array(conditionSchema).max(20, 'At most 20 conditions').optional(),
  combine: z.enum(['and', 'or']).optional(),
  sort: z.enum(['updated', 'created', 'name', 'company', 'followUp', 'city']).optional(),
  dir: z.enum(['asc', 'desc']).optional(),
});
const pagedQuery = querySchema.extend({
  page: z.number().int().min(1).max(10_000).default(1),
  limit: z.number().int().min(1).max(100).default(25),
});

const ids = z.array(z.string().uuid()).min(1, 'Select at least one contact').max(1000, 'At most 1,000 contacts at a time');
const bulkSchema = z.discriminatedUnion('action', [
  z.object({ action: z.literal('status'), ids, value: z.enum(contacts.CONTACT_STATUSES as [string, ...string[]]) }),
  z.object({ action: z.literal('owner'), ids, value: z.string().uuid().nullable() }),
  z.object({ action: z.enum(['addToList', 'removeFromList']), ids, value: z.string().uuid('Pick a list') }),
  z.object({ action: z.enum(['addTag', 'removeTag']), ids, value: text('Tag', 40).pipe(z.string().min(1, 'Enter a tag')) }),
  z.object({ action: z.literal('delete'), ids }),
]);

const importSchema = z.object({
  rows: z
    .array(z.object({ row: z.number().int().min(1) }).catchall(z.union([z.string().max(2000), z.number(), z.null()]).transform((v) => (v === null ? '' : String(v)))))
    .min(1, 'No rows to import')
    .max(500, 'Send at most 500 rows at a time'),
  duplicateMode: z.enum(['skip', 'update', 'create']).default('skip'),
  listId: z.string().uuid().nullable().optional(),
  ownerId: z.string().uuid().nullable().optional(),
  defaultStatus: z.enum(contacts.CONTACT_STATUSES as [string, ...string[]]).optional(),
  defaultSource: z.string().trim().max(60).nullable().optional(),
  fileName: z.string().trim().max(200).nullable().optional(),
});

const LIST_COLOR = z.enum(lists.LIST_COLORS);
const listCreate = z.object({
  name: text('Name', 80).pipe(z.string().min(1, 'Name is required')),
  description: opt('Description', 255),
  color: LIST_COLOR.optional(),
});
const listUpdate = listCreate.partial().refine((v) => Object.values(v).some((x) => x !== undefined), 'Nothing to update');
const memberSchema = z.object({ contactIds: ids });

const idParam = z.object({ id: z.string().uuid('Invalid id') });
const otpVerify = z.object({ challengeId: z.string().uuid('Invalid verification reference'), code: z.string().trim().regex(/^\d{6}$/, 'Enter the 6-digit code from the email') });
const otpResend = z.object({ challengeId: z.string().uuid('Invalid verification reference') });

type Q = contacts.ContactQuery;

// ── Step-up code ───────────────────────────────────────────────────────────

crmRecordsRouter.post(
  '/step-up',
  asyncHandler(async (req: Request, res: Response) => {
    res.json(await startStepUp(req.user!.sub));
  }),
);
crmRecordsRouter.post(
  '/step-up/resend',
  asyncHandler(async (req: Request, res: Response) => {
    res.json(await resendStepUp(req.user!.sub, otpResend.parse(req.body).challengeId));
  }),
);
crmRecordsRouter.post(
  '/step-up/verify-totp',
  asyncHandler(async (req: Request, res: Response) => {
    const { code } = z.object({ code: z.string().trim().regex(/^\d{6}$/, 'Enter the 6-digit code from your authenticator app') }).parse(req.body);
    res.json(await verifyStepUpTotp(req.user!.sub, code));
  }),
);
crmRecordsRouter.post(
  '/step-up/verify',
  asyncHandler(async (req: Request, res: Response) => {
    const { challengeId, code } = otpVerify.parse(req.body);
    res.json(await verifyStepUp(req.user!.sub, challengeId, code));
  }),
);

// ── Contacts ───────────────────────────────────────────────────────────────

crmRecordsRouter.post(
  '/contacts/query',
  asyncHandler(async (req: Request, res: Response) => {
    const { page, limit, ...query } = pagedQuery.parse(req.body ?? {});
    res.json(await contacts.queryContacts(query as Q, page, limit));
  }),
);

crmRecordsRouter.get(
  '/contacts/facets',
  asyncHandler(async (_req: Request, res: Response) => {
    res.json(await contacts.facets());
  }),
);

crmRecordsRouter.get(
  '/contacts/duplicates',
  asyncHandler(async (req: Request, res: Response) => {
    const q = z
      .object({ email: z.string().max(160).optional(), phone: z.string().max(20).optional(), excludeId: z.string().uuid().optional() })
      .parse(req.query);
    res.json({ duplicates: await contacts.findDuplicates(q.email, q.phone, q.excludeId) });
  }),
);

crmRecordsRouter.post(
  '/contacts/bulk',
  asyncHandler(async (req: Request, res: Response) => {
    const op = bulkSchema.parse(req.body);
    if (op.action === 'delete') assertStepUp(req);
    const { ids: chosen, ...action } = op;
    res.json(await contacts.bulk(chosen, action as contacts.BulkAction, actorOf(res)));
  }),
);

crmRecordsRouter.post(
  '/contacts/import',
  asyncHandler(async (req: Request, res: Response) => {
    const { rows, ...opts } = importSchema.parse(req.body);
    const allowed = new Set<string>(IMPORT_FIELDS);
    // Keep only columns the importer knows; the rest of a CSV is ignored.
    const clean = rows.map((r) => Object.fromEntries(Object.entries(r).filter(([k]) => k === 'row' || allowed.has(k)))) as Parameters<typeof importContacts>[0];
    res.json(await importContacts(clean, opts as Parameters<typeof importContacts>[1], actorOf(res)));
  }),
);

crmRecordsRouter.post(
  '/contacts/export',
  requireStepUp,
  asyncHandler(async (req: Request, res: Response) => {
    const query = querySchema.parse(req.body ?? {});
    const { csv, count } = await exportContacts(query as Q);
    const day = new Date().toISOString().slice(0, 10);
    res.setHeader('Content-Type', 'text/csv; charset=utf-8');
    res.setHeader('Content-Disposition', `attachment; filename="hostelcare-contacts-${day}.csv"`);
    res.setHeader('X-Row-Count', String(count));
    res.send(csv);
  }),
);

crmRecordsRouter.post(
  '/contacts',
  asyncHandler(async (req: Request, res: Response) => {
    const input = createSchema.parse(req.body) as contacts.ContactInput & { firstName: string };
    res.status(201).json({ contact: await contacts.createContact(input, actorOf(res)) });
  }),
);

crmRecordsRouter.get(
  '/contacts/:id',
  asyncHandler(async (req: Request, res: Response) => {
    const { id } = idParam.parse(req.params);
    res.json({ contact: await contacts.getContact(id) });
  }),
);

crmRecordsRouter.patch(
  '/contacts/:id',
  asyncHandler(async (req: Request, res: Response) => {
    const { id } = idParam.parse(req.params);
    const input = updateSchema.parse(req.body) as contacts.ContactInput;
    res.json({ contact: await contacts.updateContact(id, input, actorOf(res)) });
  }),
);

crmRecordsRouter.delete(
  '/contacts/:id',
  requireStepUp,
  asyncHandler(async (req: Request, res: Response) => {
    const { id } = idParam.parse(req.params);
    await contacts.deleteContact(id, actorOf(res));
    res.status(204).send();
  }),
);

crmRecordsRouter.get(
  '/contacts/:id/timeline',
  asyncHandler(async (req: Request, res: Response) => {
    const { id } = idParam.parse(req.params);
    const { before } = z.object({ before: z.string().datetime({ offset: true }).optional() }).parse(req.query);
    res.json(await contacts.timeline(id, before ? new Date(before) : undefined));
  }),
);

crmRecordsRouter.post(
  '/contacts/:id/notes',
  asyncHandler(async (req: Request, res: Response) => {
    const { id } = idParam.parse(req.params);
    // A call can be logged on a contact too (L1): it is the lead's first contact.
    const { body, type } = z
      .object({ body: text('Note', 5000, true).pipe(z.string().min(1, 'Write a note first')), type: z.enum(['NOTE', 'CALL']).default('NOTE') })
      .parse(req.body);
    res.status(201).json({ activity: await contacts.addNote(id, body, actorOf(res), type) });
  }),
);

crmRecordsRouter.post(
  '/contacts/:id/restore',
  asyncHandler(async (req: Request, res: Response) => {
    const { id } = idParam.parse(req.params);
    res.json({ contact: await contacts.restoreContact(id, actorOf(res)) });
  }),
);

crmRecordsRouter.get(
  '/bin/contacts',
  asyncHandler(async (req: Request, res: Response) => {
    const q = z
      .object({ q: z.string().trim().max(200).optional(), page: z.coerce.number().int().min(1).default(1), limit: z.coerce.number().int().min(1).max(100).default(25) })
      .parse(req.query);
    res.json(await contacts.listBin(q.q, q.page, q.limit));
  }),
);

// ── Lists ──────────────────────────────────────────────────────────────────

crmRecordsRouter.get(
  '/lists',
  asyncHandler(async (req: Request, res: Response) => {
    const { q } = z.object({ q: z.string().trim().max(100).optional() }).parse(req.query);
    res.json({ lists: await lists.listLists(q) });
  }),
);

crmRecordsRouter.post(
  '/lists',
  asyncHandler(async (req: Request, res: Response) => {
    res.status(201).json({ list: await lists.createList(listCreate.parse(req.body), actorOf(res)) });
  }),
);

crmRecordsRouter.get(
  '/lists/:id',
  asyncHandler(async (req: Request, res: Response) => {
    const { id } = idParam.parse(req.params);
    res.json({ list: await lists.getList(id) });
  }),
);

crmRecordsRouter.patch(
  '/lists/:id',
  asyncHandler(async (req: Request, res: Response) => {
    const { id } = idParam.parse(req.params);
    res.json({ list: await lists.updateList(id, listUpdate.parse(req.body)) });
  }),
);

crmRecordsRouter.delete(
  '/lists/:id',
  asyncHandler(async (req: Request, res: Response) => {
    const { id } = idParam.parse(req.params);
    await lists.deleteList(id, actorOf(res));
    res.status(204).send();
  }),
);

crmRecordsRouter.post(
  '/lists/:id/members',
  asyncHandler(async (req: Request, res: Response) => {
    const { id } = idParam.parse(req.params);
    const { contactIds } = memberSchema.parse(req.body);
    res.json({ added: await lists.addMembers(id, contactIds, actorOf(res)) });
  }),
);

crmRecordsRouter.post(
  '/lists/:id/members/remove',
  asyncHandler(async (req: Request, res: Response) => {
    const { id } = idParam.parse(req.params);
    const { contactIds } = memberSchema.parse(req.body);
    res.json({ removed: await lists.removeMembers(id, contactIds, actorOf(res)) });
  }),
);
