import { CrmStageKind, Prisma } from '@prisma/client';
import { prismaUnscoped } from '../../lib/prisma';
import { BadRequestError, ConflictError, NotFoundError } from '../../lib/errors';

/**
 * The deals pipeline: the columns of the board.
 *
 * Open stages come first, in the order the super admin sets; the one WON and
 * the one LOST stage always close the board. WON and LOST can be renamed and
 * recoloured but not removed, and their win chance is fixed at 100 and 0.
 * A stage with deals is removed only by naming where its deals go.
 */

export const STAGE_COLORS = ['slate', 'blue', 'teal', 'purple', 'amber', 'pink', 'green', 'red'] as const;
export type StageColor = (typeof STAGE_COLORS)[number];

/** Stages the automation moves deals into, found by key so a rename is safe. */
export const STAGE_KEYS = {
  NEW_LEAD: 'NEW_LEAD',
  CONTACTED: 'CONTACTED',
  DEMO_SCHEDULED: 'DEMO_SCHEDULED',
  DEMO_DONE: 'DEMO_DONE',
  TRIAL_STARTED: 'TRIAL_STARTED',
  TRIAL_ACTIVE: 'TRIAL_ACTIVE',
} as const;
export type StageKey = (typeof STAGE_KEYS)[keyof typeof STAGE_KEYS];

/** What each keyed stage is for, in the words the delete refusal uses. */
const KEY_PURPOSE: Record<string, string> = {
  TRIAL_STARTED: 'is where free trials land',
  TRIAL_ACTIVE: 'is where trials that collect rent land',
  DEMO_SCHEDULED: 'is where booked demos land',
  DEMO_DONE: 'is where held demos land',
};
/** The default name each keyed stage is adopted by, when an older pipeline has it unkeyed. */
const KEY_NAMES: Record<StageKey, string[]> = {
  NEW_LEAD: ['New lead'],
  CONTACTED: ['Contacted'],
  DEMO_SCHEDULED: ['Demo scheduled', 'Demo booked'],
  DEMO_DONE: ['Demo done'],
  TRIAL_STARTED: ['Trial started'],
  TRIAL_ACTIVE: ['Trial active'],
};

const DEFAULTS: { name: string; probability: number; kind: CrmStageKind; color: StageColor; key?: string }[] = [
  { name: 'New lead', probability: 10, kind: CrmStageKind.OPEN, color: 'slate', key: STAGE_KEYS.NEW_LEAD },
  { name: 'Contacted', probability: 20, kind: CrmStageKind.OPEN, color: 'blue', key: STAGE_KEYS.CONTACTED },
  { name: 'Demo scheduled', probability: 40, kind: CrmStageKind.OPEN, color: 'teal', key: STAGE_KEYS.DEMO_SCHEDULED },
  { name: 'Demo done', probability: 50, kind: CrmStageKind.OPEN, color: 'purple', key: STAGE_KEYS.DEMO_DONE },
  { name: 'Trial started', probability: 60, kind: CrmStageKind.OPEN, color: 'teal', key: STAGE_KEYS.TRIAL_STARTED },
  // L5: the plan's eight stages. Older pipelines keep their Proposal / Negotiation stages.
  { name: 'Trial active', probability: 80, kind: CrmStageKind.OPEN, color: 'green', key: STAGE_KEYS.TRIAL_ACTIVE },
  { name: 'Won', probability: 100, kind: CrmStageKind.WON, color: 'green' },
  { name: 'Lost', probability: 0, kind: CrmStageKind.LOST, color: 'red' },
];

/** The migration seeds the pipeline; a schema built another way gets it here. */
export async function ensureStages() {
  if ((await prismaUnscoped.crmStage.count()) > 0) return;
  await prismaUnscoped.$transaction(async (tx) => {
    // Two first requests at once: the advisory lock lets only one seed.
    await tx.$executeRaw`SELECT pg_advisory_xact_lock(7300001)`;
    if ((await tx.crmStage.count()) > 0) return;
    await tx.crmStage.createMany({ data: DEFAULTS.map((d, i) => ({ ...d, position: i + 1 })) });
  });
}

/**
 * A demo stage (L3) by key; an open stage still carrying the default name is
 * adopted. Null if the team removed it before it was keyed: the deal then
 * stays where it is.
 */
export async function demoStage(key: typeof STAGE_KEYS.DEMO_SCHEDULED | typeof STAGE_KEYS.DEMO_DONE) {
  await ensureStages();
  const found = await prismaUnscoped.crmStage.findUnique({ where: { key } });
  if (found) return found;
  const names = key === STAGE_KEYS.DEMO_DONE ? ['Demo done'] : ['Demo scheduled', 'Demo booked'];
  const named = await prismaUnscoped.crmStage.findFirst({ where: { kind: CrmStageKind.OPEN, key: null, OR: names.map((n) => ({ name: { equals: n, mode: 'insensitive' as const } })) }, orderBy: { position: 'asc' } });
  if (!named) return null;
  return prismaUnscoped.crmStage.update({ where: { id: named.id }, data: { key } }).catch(() => prismaUnscoped.crmStage.findUnique({ where: { key } }));
}

/**
 * The stage a self-serve trial's deal opens in (L2). The migration adds it to
 * existing pipelines; this covers a schema built another way, or a pipeline
 * that somehow lost it: added after "Demo done", or before Won and Lost.
 */
export async function trialStage() {
  await ensureStages();
  const found = await prismaUnscoped.crmStage.findUnique({ where: { key: STAGE_KEYS.TRIAL_STARTED } });
  if (found) return found;
  return prismaUnscoped.$transaction(async (tx) => {
    await tx.$executeRaw`SELECT pg_advisory_xact_lock(7300002)`;
    const again = await tx.crmStage.findUnique({ where: { key: STAGE_KEYS.TRIAL_STARTED } });
    if (again) return again;
    const named = await tx.crmStage.findFirst({ where: { name: { equals: 'Trial started', mode: 'insensitive' }, kind: CrmStageKind.OPEN } });
    if (named) return tx.crmStage.update({ where: { id: named.id }, data: { key: STAGE_KEYS.TRIAL_STARTED } });
    const demoDone = await tx.crmStage.findFirst({ where: { name: { equals: 'Demo done', mode: 'insensitive' }, kind: CrmStageKind.OPEN } });
    const closing = await tx.crmStage.findFirst({ where: { kind: { not: CrmStageKind.OPEN } }, orderBy: { position: 'asc' } });
    const last = (await tx.crmStage.aggregate({ _max: { position: true } }))._max.position ?? 0;
    const at = demoDone ? demoDone.position + 1 : (closing?.position ?? last + 1);
    await tx.crmStage.updateMany({ where: { position: { gte: at } }, data: { position: { increment: 1 } } });
    const s = await tx.crmStage.create({ data: { name: 'Trial started', probability: 60, kind: CrmStageKind.OPEN, color: 'teal', key: STAGE_KEYS.TRIAL_STARTED, position: at } });
    await renumber(tx);
    return s;
  });
}

export async function listStages() {
  await ensureStages();
  const [stages, counts] = await Promise.all([
    prismaUnscoped.crmStage.findMany({ orderBy: { position: 'asc' } }),
    prismaUnscoped.crmDeal.groupBy({ by: ['stageId'], where: { deletedAt: null }, _count: { _all: true } }),
  ]);
  return stages.map((s) => ({ ...s, dealCount: counts.find((c) => c.stageId === s.id)?._count._all ?? 0 }));
}

async function load(id: string) {
  const s = await prismaUnscoped.crmStage.findUnique({ where: { id } });
  if (!s) throw new NotFoundError('Stage not found');
  return s;
}

/** Re-number so open stages run 1..n, then WON, then LOST. */
async function renumber(tx: Prisma.TransactionClient, openOrder?: string[]) {
  const all = await tx.crmStage.findMany({ orderBy: { position: 'asc' } });
  const open = all.filter((s) => s.kind === CrmStageKind.OPEN);
  if (openOrder) open.sort((a, b) => openOrder.indexOf(a.id) - openOrder.indexOf(b.id));
  const ordered = [...open, ...all.filter((s) => s.kind === CrmStageKind.WON), ...all.filter((s) => s.kind === CrmStageKind.LOST)];
  for (const [i, s] of ordered.entries()) if (s.position !== i + 1) await tx.crmStage.update({ where: { id: s.id }, data: { position: i + 1 } });
}

async function assertNameFree(name: string, exceptId?: string) {
  const clash = await prismaUnscoped.crmStage.findFirst({ where: { name: { equals: name, mode: 'insensitive' }, ...(exceptId ? { id: { not: exceptId } } : {}) } });
  if (clash) throw new ConflictError('A stage with that name already exists.', 'STAGE_NAME_TAKEN');
}

export async function createStage(input: { name: string; probability: number; color?: StageColor }) {
  await ensureStages();
  await assertNameFree(input.name);
  if ((await prismaUnscoped.crmStage.count({ where: { kind: CrmStageKind.OPEN } })) >= 15) {
    throw new BadRequestError('A pipeline can have at most 15 open stages.');
  }
  return prismaUnscoped.$transaction(async (tx) => {
    const s = await tx.crmStage.create({ data: { name: input.name, probability: input.probability, color: input.color ?? 'blue', kind: CrmStageKind.OPEN, position: 999 } });
    await renumber(tx);
    return tx.crmStage.findUniqueOrThrow({ where: { id: s.id } });
  });
}

export async function updateStage(id: string, input: { name?: string; probability?: number; color?: StageColor }) {
  const s = await load(id);
  if (input.name) await assertNameFree(input.name, id);
  if (input.probability !== undefined && s.kind !== CrmStageKind.OPEN) {
    throw new BadRequestError('Won is always 100% and Lost always 0%.', 'STAGE_PROBABILITY_FIXED');
  }
  return prismaUnscoped.crmStage.update({ where: { id }, data: input });
}

export async function reorderStages(openIds: string[]) {
  const open = await prismaUnscoped.crmStage.findMany({ where: { kind: CrmStageKind.OPEN }, select: { id: true } });
  if (open.length !== openIds.length || open.some((s) => !openIds.includes(s.id))) {
    throw new BadRequestError('Send every open stage exactly once.', 'STAGE_ORDER_INCOMPLETE');
  }
  await prismaUnscoped.$transaction(async (tx) => renumber(tx, openIds));
  return listStages();
}

export async function deleteStage(id: string, moveToId?: string) {
  const s = await load(id);
  if (s.kind !== CrmStageKind.OPEN) throw new BadRequestError('The Won and Lost stages cannot be removed.', 'STAGE_REQUIRED');
  // New lead and Contacted may go: the automation then uses the first open stage, or leaves the deal where it is.
  if (s.key && KEY_PURPOSE[s.key]) throw new BadRequestError(`"${s.name}" ${KEY_PURPOSE[s.key] ?? 'is used by the automation'}, so it cannot be removed. Rename it instead.`, 'STAGE_REQUIRED');
  const openCount = await prismaUnscoped.crmStage.count({ where: { kind: CrmStageKind.OPEN } });
  if (openCount <= 1) throw new BadRequestError('Keep at least one open stage.', 'STAGE_REQUIRED');
  const dealCount = await prismaUnscoped.crmDeal.count({ where: { stageId: id } });
  if (dealCount) {
    if (!moveToId) throw new ConflictError(`This stage has ${dealCount} deal${dealCount === 1 ? '' : 's'}. Choose a stage to move them to.`, 'STAGE_HAS_DEALS');
    const target = await load(moveToId);
    if (target.id === id || target.kind !== CrmStageKind.OPEN) throw new BadRequestError('Move the deals to another open stage.');
  }
  await prismaUnscoped.$transaction(async (tx) => {
    if (dealCount) await tx.crmDeal.updateMany({ where: { stageId: id }, data: { stageId: moveToId!, stageChangedAt: new Date() } });
    await tx.crmStage.delete({ where: { id } });
    await renumber(tx);
  });
  return listStages();
}

/**
 * Any keyed stage (L5): by key, or adopted from an unkeyed open stage with its
 * default name. "Trial active" is made after "Trial started" if missing; the
 * others are null when the team removed them.
 */
export async function stageByKey(key: StageKey) {
  if (key === STAGE_KEYS.TRIAL_STARTED) return trialStage();
  await ensureStages();
  const found = await prismaUnscoped.crmStage.findUnique({ where: { key } });
  if (found) return found;
  return prismaUnscoped.$transaction(async (tx) => {
    await tx.$executeRaw`SELECT pg_advisory_xact_lock(7300004)`;
    const again = await tx.crmStage.findUnique({ where: { key } });
    if (again) return again;
    const named = await tx.crmStage.findFirst({ where: { kind: CrmStageKind.OPEN, key: null, OR: KEY_NAMES[key].map((n) => ({ name: { equals: n, mode: 'insensitive' as const } })) }, orderBy: { position: 'asc' } });
    if (named) return tx.crmStage.update({ where: { id: named.id }, data: { key } });
    if (key !== STAGE_KEYS.TRIAL_ACTIVE) return null;
    const after = await tx.crmStage.findUnique({ where: { key: STAGE_KEYS.TRIAL_STARTED } });
    const closing = await tx.crmStage.findFirst({ where: { kind: { not: CrmStageKind.OPEN } }, orderBy: { position: 'asc' } });
    const last = (await tx.crmStage.aggregate({ _max: { position: true } }))._max.position ?? 0;
    const at = after ? after.position + 1 : (closing?.position ?? last + 1);
    await tx.crmStage.updateMany({ where: { position: { gte: at } }, data: { position: { increment: 1 } } });
    const s = await tx.crmStage.create({ data: { name: 'Trial active', probability: 80, kind: CrmStageKind.OPEN, color: 'green', key, position: at } });
    await renumber(tx);
    return s;
  });
}
