import { Router, Request, Response } from 'express';
import { z } from 'zod';
import { Role } from '@prisma/client';
import { asyncHandler } from '../../middleware/asyncHandler';
import { authorize } from '../../middleware/authorize';
import { actorOf } from './crm-access';
import * as ai from './crm-ai.service';
import { rescoreDeal } from './crm-ai-scoring';
import { CLEANUP_FIELDS, applyCleanup, cleanupSuggestions } from './crm-ai-cleanup';
import { INSIGHT_PERIODS, campaignIdeas, createInsightReport, getInsightReport, listInsightReports } from './crm-ai-marketing';
import * as assistant from './crm-ai-assistant';

/**
 * CRM AI endpoints. Mounted on crmRouter after requireCrmAccess. Each answer
 * is a suggestion the person then confirms. The exceptions are deliberate:
 * a lead score is saved as soon as it is made, an insights report is saved
 * so the team can come back to it, and clean-up fixes are saved only when a
 * person applies the ones they ticked.
 */
export const crmAiRouter = Router();

const idParam = z.object({ id: z.string().uuid('Invalid id') });

crmAiRouter.get(
  '/ai/status',
  asyncHandler(async (_req: Request, res: Response) => {
    res.json({ ai: await ai.aiStatus() });
  }),
);

crmAiRouter.post(
  '/ai/capture',
  asyncHandler(async (req: Request, res: Response) => {
    const body = z.object({ text: z.string().max(8000).optional(), image: z.string().max(6_000_000).optional() }).parse(req.body);
    res.json({ contact: await ai.capture(body, actorOf(res)) });
  }),
);

crmAiRouter.post(
  '/ai/filter',
  asyncHandler(async (req: Request, res: Response) => {
    const { text } = z.object({ text: z.string().trim().min(1, 'Say who you are looking for').max(500) }).parse(req.body);
    res.json({ filter: await ai.filterFromWords(text, actorOf(res)) });
  }),
);

crmAiRouter.post(
  '/ai/deals/:id/summary',
  asyncHandler(async (req: Request, res: Response) => {
    res.json({ summary: await ai.dealSummary(idParam.parse(req.params).id, actorOf(res)) });
  }),
);

crmAiRouter.post(
  '/ai/deals/:id/notes-to-tasks',
  asyncHandler(async (req: Request, res: Response) => {
    const { id } = idParam.parse(req.params);
    const { notes } = z.object({ notes: z.string().trim().min(1, 'Type your notes first').max(8000) }).parse(req.body);
    res.json({ result: await ai.notesToTasks(id, notes, actorOf(res)) });
  }),
);

crmAiRouter.post(
  '/ai/draft-email',
  asyncHandler(async (req: Request, res: Response) => {
    const body = z
      .object({
        dealId: z.string().uuid().optional(),
        contactId: z.string().uuid().optional(),
        purpose: z.enum(ai.DRAFT_PURPOSES),
        instructions: z.string().trim().max(2000).optional(),
        incoming: z.string().trim().max(6000).optional(),
      })
      .refine((b) => b.dealId || b.contactId, 'Pick a deal or a contact')
      .parse(req.body);
    res.json({ draft: await ai.draftEmail(body, actorOf(res)) });
  }),
);

// ── C6: lead scores, clean-up, insights, campaigns ─────────────────────────

crmAiRouter.post(
  '/ai/deals/:id/score',
  asyncHandler(async (req: Request, res: Response) => {
    res.json({ score: await rescoreDeal(idParam.parse(req.params).id, actorOf(res)) });
  }),
);

crmAiRouter.post(
  '/ai/cleanup',
  asyncHandler(async (_req: Request, res: Response) => {
    res.json({ cleanup: await cleanupSuggestions(actorOf(res)) });
  }),
);

crmAiRouter.post(
  '/ai/cleanup/apply',
  asyncHandler(async (req: Request, res: Response) => {
    const { fixes } = z
      .object({
        fixes: z
          .array(z.object({ contactId: z.string().uuid(), field: z.enum(CLEANUP_FIELDS), from: z.string().max(200), to: z.string().trim().min(1).max(160) }))
          .min(1, 'Pick at least one fix')
          .max(100),
      })
      .parse(req.body);
    res.json({ result: await applyCleanup(fixes, actorOf(res)) });
  }),
);

crmAiRouter.get(
  '/ai/insights',
  asyncHandler(async (_req: Request, res: Response) => {
    res.json({ reports: await listInsightReports() });
  }),
);

crmAiRouter.get(
  '/ai/insights/:id',
  asyncHandler(async (req: Request, res: Response) => {
    res.json({ report: await getInsightReport(idParam.parse(req.params).id) });
  }),
);

crmAiRouter.post(
  '/ai/insights',
  asyncHandler(async (req: Request, res: Response) => {
    const { period } = z.object({ period: z.enum(INSIGHT_PERIODS) }).parse(req.body);
    res.status(201).json({ report: await createInsightReport(period, actorOf(res)) });
  }),
);

crmAiRouter.post(
  '/ai/lists/:id/campaign',
  asyncHandler(async (req: Request, res: Response) => {
    const { id } = idParam.parse(req.params);
    const body = z.object({ goal: z.string().trim().max(500).optional(), angle: z.string().trim().max(200).optional() }).parse(req.body ?? {});
    res.json({ campaign: await campaignIdeas(id, body, actorOf(res)) });
  }),
);

// ── C7: the assistant (super admin only) ───────────────────────────────────

const superOnly = authorize(Role.SUPER_ADMIN);

crmAiRouter.get(
  '/ai/assistant/threads',
  superOnly,
  asyncHandler(async (_req: Request, res: Response) => {
    res.json({ threads: await assistant.listThreads(actorOf(res)) });
  }),
);

crmAiRouter.get(
  '/ai/assistant/threads/:id',
  superOnly,
  asyncHandler(async (req: Request, res: Response) => {
    res.json(await assistant.getThread(idParam.parse(req.params).id, actorOf(res)));
  }),
);

crmAiRouter.delete(
  '/ai/assistant/threads/:id',
  superOnly,
  asyncHandler(async (req: Request, res: Response) => {
    await assistant.deleteThread(idParam.parse(req.params).id, actorOf(res));
    res.status(204).send();
  }),
);

crmAiRouter.post(
  '/ai/assistant/messages',
  superOnly,
  asyncHandler(async (req: Request, res: Response) => {
    const body = z.object({ threadId: z.string().uuid().nullable().optional(), text: z.string().trim().min(1, 'Type a question or a request').max(4000) }).parse(req.body);
    res.json(await assistant.ask(body, actorOf(res)));
  }),
);

crmAiRouter.post(
  '/ai/assistant/actions/:id/confirm',
  superOnly,
  asyncHandler(async (req: Request, res: Response) => {
    res.json(await assistant.confirmAction(idParam.parse(req.params).id, actorOf(res)));
  }),
);

crmAiRouter.post(
  '/ai/assistant/actions/:id/cancel',
  superOnly,
  asyncHandler(async (req: Request, res: Response) => {
    res.json(await assistant.cancelAction(idParam.parse(req.params).id, actorOf(res)));
  }),
);

crmAiRouter.get(
  '/ai/usage',
  authorize(Role.SUPER_ADMIN),
  asyncHandler(async (_req: Request, res: Response) => {
    res.json({ usage: await ai.usageReport() });
  }),
);
