import { CrmStageKind } from '@prisma/client';
import { prismaUnscoped } from '../../lib/prisma';
import { BadRequestError } from '../../lib/errors';
import { moveDeal } from './crm-deals.service';
import { getCrmSettings } from './crm-settings.service';
import { stageByKey, type StageKey } from './crm-stages.service';
import type { Actor } from './crm-users.service';

/**
 * The pipeline's rules (Sprint L5): the eight stages and what entering each
 * one does. Automatic moves only ever go forward; a person moving a deal on
 * sets the next step's date first, so no deal is left without one.
 */

/** The CRM clock and the webhooks act as this. */
export const SYSTEM_ACTOR: Actor = { id: 'system', name: 'HostelCare (automatic)', email: '' };

/**
 * Move a deal forward to a keyed stage — never backward, never out of Won
 * or Lost — and set what happens next. Returns whether it moved.
 */
export async function advanceDeal(dealId: string, key: StageKey, actor: Actor, next?: { nextStep?: string | null; nextActionAt?: Date | null }) {
  const [deal, target] = await Promise.all([prismaUnscoped.crmDeal.findFirst({ where: { id: dealId, deletedAt: null }, include: { stage: true } }), stageByKey(key)]);
  if (!deal || !target || deal.stage.kind !== CrmStageKind.OPEN || deal.stageId === target.id || deal.stage.position > target.position) return false;
  await moveDeal(dealId, { stageId: target.id }, actor);
  if (next) {
    await prismaUnscoped.crmDeal.update({
      where: { id: dealId },
      data: { ...(next.nextStep !== undefined ? { nextStep: next.nextStep } : {}), ...(next.nextActionAt !== undefined ? { nextActionAt: next.nextActionAt } : {}) },
    });
  }
  return true;
}

/**
 * A person moving a deal on to a later open stage must say when the next
 * step is: in the same request, or already set in the future. Super admin
 * can switch the rule off in CRM settings.
 */
export async function assertNextStep(dealId: string, stageId: string, nextActionAt: Date | null | undefined, now = new Date()) {
  if (!(await getCrmSettings()).requireNextStep) return;
  const [deal, target] = await Promise.all([
    prismaUnscoped.crmDeal.findFirst({ where: { id: dealId, deletedAt: null }, include: { stage: true } }),
    prismaUnscoped.crmStage.findUnique({ where: { id: stageId } }),
  ]);
  if (!deal || !target) return; // the move itself reports these
  const forward = deal.stage.kind === CrmStageKind.OPEN && target.kind === CrmStageKind.OPEN && target.position > deal.stage.position;
  if (!forward) return;
  const when = nextActionAt ?? deal.nextActionAt;
  if (!when || when.getTime() <= now.getTime()) {
    throw new BadRequestError('Set the date of the next step before moving the deal on.', 'NEXT_STEP_REQUIRED');
  }
}
