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 { env } from '../../config/env';
import { actorOf } from './crm-access';
import { TEAM_LOST_REASONS } from './crm-deals.service';
import { CALL_OUTCOMES, contactTasks, logCallOutcome, metaLeadLog } from './crm-touch.service';
import { extendTrialFromCrm } from './crm-trials.service';

/**
 * Sprint L4, behind requireCrmAccess: the one-tap call outcome on a contact,
 * the contact's open call-backs, and (super admin) the Meta lead log.
 */
export const crmTouchRouter = Router();

const idParam = z.object({ id: z.string().uuid('Invalid id') });
const outcomeSchema = z.object({
  outcome: z.enum(CALL_OUTCOMES),
  note: z.string().trim().max(2000).optional().nullable(),
  followUpAt: z.string().datetime({ offset: true, message: 'Pick a date and time' }).optional().nullable(),
  reason: z.enum(TEAM_LOST_REASONS).optional().nullable(),
  /** Test clock, like /dev/tick: honoured only where CRM_TEST_CLOCK is on. */
  at: z.string().datetime({ offset: true }).optional(),
});

crmTouchRouter.post(
  '/contacts/:id/call-outcome',
  asyncHandler(async (req: Request, res: Response) => {
    const { id } = idParam.parse(req.params);
    const b = outcomeSchema.parse(req.body ?? {});
    const now = b.at && env.CRM_TEST_CLOCK && env.NODE_ENV !== 'production' ? new Date(b.at) : new Date();
    res.status(201).json(await logCallOutcome(id, { outcome: b.outcome, note: b.note, followUpAt: b.followUpAt ? new Date(b.followUpAt) : null, reason: b.reason ?? null }, actorOf(res), now));
  }),
);

crmTouchRouter.get(
  '/contacts/:id/tasks',
  asyncHandler(async (req: Request, res: Response) => {
    res.json({ tasks: await contactTasks(idParam.parse(req.params).id) });
  }),
);

/** The one 7-day extension of an active trial (L5). */
crmTouchRouter.post(
  '/deals/:id/extend-trial',
  asyncHandler(async (req: Request, res: Response) => {
    const { id } = idParam.parse(req.params);
    const { at } = z.object({ at: z.string().datetime({ offset: true }).optional() }).parse(req.body ?? {});
    const now = at && env.CRM_TEST_CLOCK && env.NODE_ENV !== 'production' ? new Date(at) : new Date();
    res.json(await extendTrialFromCrm(id, actorOf(res), now));
  }),
);

crmTouchRouter.get(
  '/meta-leads',
  authorize(Role.SUPER_ADMIN),
  asyncHandler(async (req: Request, res: Response) => {
    const { limit } = z.object({ limit: z.coerce.number().int().min(1).max(200).default(50) }).parse(req.query);
    res.json({ leads: await metaLeadLog(limit) });
  }),
);
