import { Router, Request, Response } from 'express';
import { z } from 'zod';
import { CrmStageKind, Role } from '@prisma/client';
import { asyncHandler } from '../../middleware/asyncHandler';
import { prismaUnscoped } from '../../lib/prisma';
import { BadRequestError, NotFoundError } from '../../lib/errors';
import { actorOf } from './crm-access';
import { dealRef, logActivity, updateDeal, updateTask } from './crm-deals.service';
import { addNote, fullName, updateContact } from './crm-contacts.service';
import type { Actor } from './crm-users.service';

/**
 * The follow-up dashboard (10 Oct 2026): every dated thing someone has to do —
 * a deal's next action, a contact's follow-up, a task — for a day or a week,
 * plus everything overdue, with the actions that clear them.
 *
 * Done: a task is finished; a deal's next step is cleared and noted on its
 * timeline; a contact is marked contacted now and its follow-up cleared.
 * Reschedule moves the date. Both go through the usual services, so the
 * timeline, alerts and reminders behave exactly as for an edit by hand.
 * Mounted on crmRouter after requireCrmAccess: one shared workspace.
 */

export const crmFollowUpsRouter = Router();

const IST = '+05:30';
const DAY = 86_400_000;
const OVERDUE_DAYS = 90;
const CAP = 500;

type Kind = 'deal' | 'contact' | 'task';

export interface FollowUp {
  key: string;
  kind: Kind;
  id: string;
  at: Date;
  title: string;
  sub: string | null;
  ownerId: string | null;
  ownerName: string | null;
  /** Where it opens: the deal (for a deal or its task) or the contact. */
  dealId: string | null;
  contactId: string | null;
  value: number | null;
}

async function gather(range: { gte?: Date; lt: Date }, ownerId: string | 'none' | null, kinds: Set<Kind>): Promise<FollowUp[]> {
  const owner = <K extends string>(field: K) => (ownerId === null ? {} : ({ [field]: ownerId === 'none' ? null : ownerId } as Record<K, string | null>));
  const [deals, contacts, tasks] = await Promise.all([
    kinds.has('deal')
      ? prismaUnscoped.crmDeal.findMany({
          where: { deletedAt: null, stage: { kind: CrmStageKind.OPEN }, nextActionAt: range, ...owner('assigneeId') },
          orderBy: { nextActionAt: 'asc' },
          take: CAP,
          select: { id: true, number: true, title: true, value: true, nextStep: true, nextActionAt: true, assignee: { select: { id: true, name: true } }, contact: { select: { id: true, firstName: true, lastName: true, phone: true } } },
        })
      : [],
    kinds.has('contact')
      ? prismaUnscoped.crmContact.findMany({
          where: { deletedAt: null, nextFollowUpAt: range, ...owner('ownerId') },
          orderBy: { nextFollowUpAt: 'asc' },
          take: CAP,
          select: { id: true, firstName: true, lastName: true, companyName: true, phone: true, nextFollowUpAt: true, owner: { select: { id: true, name: true } } },
        })
      : [],
    kinds.has('task')
      ? prismaUnscoped.crmTask.findMany({
          where: { done: false, dueAt: range, OR: [{ dealId: null }, { deal: { deletedAt: null } }], AND: [{ OR: [{ contactId: null }, { contact: { deletedAt: null } }] }], ...owner('assigneeId') },
          orderBy: { dueAt: 'asc' },
          take: CAP,
          select: { id: true, title: true, dueAt: true, assignee: { select: { id: true, name: true } }, deal: { select: { id: true, number: true, title: true, contactId: true } }, contact: { select: { id: true, firstName: true, lastName: true, phone: true } } },
        })
      : [],
  ]);
  return [
    ...deals.map((d) => ({
      key: `deal:${d.id}`,
      kind: 'deal' as const,
      id: d.id,
      at: d.nextActionAt!,
      title: d.nextStep || `Next action on ${dealRef(d.number)}`,
      sub: [`${dealRef(d.number)} · ${d.title}`, d.contact ? `${fullName(d.contact)}${d.contact.phone ? ` · ${d.contact.phone}` : ''}` : null].filter(Boolean).join(' · '),
      ownerId: d.assignee?.id ?? null,
      ownerName: d.assignee?.name ?? null,
      dealId: d.id,
      contactId: d.contact?.id ?? null,
      value: d.value,
    })),
    ...contacts.map((c) => ({
      key: `contact:${c.id}`,
      kind: 'contact' as const,
      id: c.id,
      at: c.nextFollowUpAt!,
      title: `Follow up with ${fullName(c)}`,
      sub: [c.companyName, c.phone].filter(Boolean).join(' · ') || null,
      ownerId: c.owner?.id ?? null,
      ownerName: c.owner?.name ?? null,
      dealId: null,
      contactId: c.id,
      value: null,
    })),
    ...tasks.map((t) => ({
      key: `task:${t.id}`,
      kind: 'task' as const,
      id: t.id,
      at: t.dueAt!,
      title: t.title,
      sub: [t.contact ? `${fullName(t.contact)}${t.contact.phone ? ` · ${t.contact.phone}` : ''}` : null, t.deal ? `${dealRef(t.deal.number)} · ${t.deal.title}` : null].filter(Boolean).join(' · ') || null,
      ownerId: t.assignee?.id ?? null,
      ownerName: t.assignee?.name ?? null,
      dealId: t.deal?.id ?? null,
      contactId: t.contact?.id ?? t.deal?.contactId ?? null,
      value: null,
    })),
  ].sort((a, b) => a.at.getTime() - b.at.getTime());
}

const day = z.string().regex(/^\d{4}-\d{2}-\d{2}$/, 'Use a YYYY-MM-DD date');
const kindsOf = (type: string | undefined) => new Set<Kind>(type === 'deal' || type === 'contact' || type === 'task' ? [type] : ['deal', 'contact', 'task']);

/** The board: items from `from` to `to` (India days, inclusive), and what is overdue. */
crmFollowUpsRouter.get(
  '/follow-ups',
  asyncHandler(async (req: Request, res: Response) => {
    const q = z
      .object({ from: day, to: day, owner: z.string().optional(), type: z.enum(['all', 'deal', 'contact', 'task']).optional() })
      .refine((v) => v.to >= v.from, 'The end date is before the start')
      .refine((v) => Date.parse(v.to) - Date.parse(v.from) <= 42 * DAY, 'Six weeks at most')
      .parse(req.query);
    const me = actorOf(res).id;
    const ownerId = !q.owner || q.owner === 'all' ? null : q.owner === 'me' ? me : q.owner === 'none' ? 'none' : z.string().uuid().parse(q.owner);
    const kinds = kindsOf(q.type);
    const now = new Date();
    const start = new Date(`${q.from}T00:00:00${IST}`);
    const end = new Date(Date.parse(`${q.to}T00:00:00${IST}`) + DAY);
    const todayStart = new Date(`${new Date(now.getTime() + 330 * 60_000).toISOString().slice(0, 10)}T00:00:00${IST}`);
    const [items, overdue, today, week] = await Promise.all([
      gather({ gte: start, lt: end }, ownerId, kinds),
      gather({ gte: new Date(now.getTime() - OVERDUE_DAYS * DAY), lt: now }, ownerId, kinds),
      gather({ gte: todayStart, lt: new Date(todayStart.getTime() + DAY) }, ownerId, kinds),
      gather({ gte: todayStart, lt: new Date(todayStart.getTime() + 7 * DAY) }, ownerId, kinds),
    ]);
    const members = await prismaUnscoped.user.findMany({ where: { role: { in: [Role.CRM_USER, Role.SUPER_ADMIN] }, deactivatedAt: null }, select: { id: true, name: true }, orderBy: { name: 'asc' } });
    res.json({
      range: { from: q.from, to: q.to },
      items,
      overdue,
      counts: { overdue: overdue.length, today: today.filter((i) => i.at >= now).length, next7: week.filter((i) => i.at >= now).length, inRange: items.length },
      members,
    });
  }),
);

const target = z.object({ kind: z.enum(['deal', 'contact', 'task']), id: z.string().uuid() });

async function complete(kind: Kind, id: string, note: string | undefined, actor: Actor) {
  if (kind === 'task') {
    await updateTask(id, { done: true }, actor);
    return;
  }
  if (kind === 'deal') {
    const d = await prismaUnscoped.crmDeal.findFirst({ where: { id, deletedAt: null }, select: { nextStep: true } });
    if (!d) throw new NotFoundError('Deal not found');
    await logActivity(id, { type: 'NOTE', body: `Done: ${d.nextStep || 'next action'}${note ? ` — ${note}` : ''}` }, actor);
    await updateDeal(id, { nextStep: null, nextActionAt: null }, actor);
    return;
  }
  await updateContact(id, { nextFollowUpAt: null, lastContactedAt: new Date() }, actor);
  if (note) await addNote(id, note, actor);
}

async function reschedule(kind: Kind, id: string, at: Date, actor: Actor) {
  if (kind === 'task') await updateTask(id, { dueAt: at }, actor);
  else if (kind === 'deal') await updateDeal(id, { nextActionAt: at }, actor);
  else await updateContact(id, { nextFollowUpAt: at }, actor);
}

crmFollowUpsRouter.post(
  '/follow-ups/complete',
  asyncHandler(async (req: Request, res: Response) => {
    const b = target.extend({ note: z.string().trim().max(1000).optional() }).parse(req.body);
    await complete(b.kind, b.id, b.note || undefined, actorOf(res));
    res.json({ ok: true });
  }),
);

crmFollowUpsRouter.post(
  '/follow-ups/reschedule',
  asyncHandler(async (req: Request, res: Response) => {
    const b = target.extend({ at: z.string().datetime({ offset: true, message: 'Enter a valid date and time' }) }).parse(req.body);
    const at = new Date(b.at);
    if (at.getTime() < Date.now() - 5 * 60_000) throw new BadRequestError('Pick a time from now on.', 'IN_THE_PAST');
    await reschedule(b.kind, b.id, at, actorOf(res));
    res.json({ ok: true });
  }),
);

