import { CrmActivityType, CrmContactStatus, CrmStageKind, Prisma } from '@prisma/client';
import { prismaUnscoped } from '../../lib/prisma';
import { BadRequestError, NotFoundError } from '../../lib/errors';
import type { Actor } from './crm-users.service';
import { addToNurture, assertMember, BIN_DAYS, fullName, hostelAccountOf, markTouched } from './crm-contacts.service';
import { ensureStages, trialStage } from './crm-stages.service';
import { getCrmSettings } from './crm-settings.service';
import { notify } from './crm-notify';
import { crmUrl, fmtIst, rupees } from './crm-mail';
import { describeChanges } from './crm-contacts.service';

/**
 * CRM deals: the pipeline of sales the team is working.
 *
 * Every deal sits in a stage (a board column) at a position within it, has an
 * assignee, a value in whole rupees and a win chance (its own, or its
 * stage's). Moving into the WON stage stamps wonAt and makes the main contact
 * a Customer; moving into LOST needs a reason; moving back out reopens it.
 * Deleting puts it in the bin for 30 days, as with contacts.
 *
 * Headline events (created, moved, won, lost, reopened, notes, calls,
 * meetings) also carry the main contact, so they show on that contact's
 * timeline too.
 */

export const dealRef = (n: number) => `DEAL-${String(n).padStart(4, '0')}`;

/**
 * Why deals are lost, as fixed codes for reporting (L4). The first five are
 * the team's choices; the rest are set by the automation.
 */
export const LOST_REASONS = {
  PRICE: 'Price',
  EXCEL: 'Happy with Excel',
  TOO_SMALL: 'Too small',
  HAS_SOFTWARE: 'Has software',
  OTHER: 'Other',
  NO_ANSWER: 'No answer after 3 calls',
  WRONG_NUMBER: 'Wrong number',
  NOT_A_FIT: 'Not a fit',
  MISSED_DEMOS: 'Missed two demos',
  TRIAL_NOT_USED: 'Trial not used',
} as const;
export type LostReasonCode = keyof typeof LOST_REASONS;
export const TEAM_LOST_REASONS = ['PRICE', 'EXCEL', 'TOO_SMALL', 'HAS_SOFTWARE', 'OTHER'] as const;

export interface DealInput {
  title?: string;
  value?: number;
  stageId?: string;
  probability?: number | null;
  expectedCloseDate?: Date | null;
  assigneeId?: string | null;
  contactId?: string | null;
  contactIds?: string[];
  companyName?: string | null;
  source?: string | null;
  planInterest?: string | null;
  beds?: number | null;
  nextStep?: string | null;
  nextActionAt?: Date | null;
  description?: string | null;
  lostReason?: string | null;
}

const LABEL: Record<string, string> = {
  title: 'Title',
  value: 'Value',
  probability: 'Win chance',
  expectedCloseDate: 'Expected close',
  assigneeId: 'Assignee',
  contactId: 'Main contact',
  companyName: 'Company',
  source: 'Source',
  planInterest: 'Plan of interest',
  beds: 'Beds',
  nextStep: 'Next step',
  nextActionAt: 'Next action',
  description: 'Description',
  lostReason: 'Lost reason',
};

// ── Shapes ─────────────────────────────────────────────────────────────────

const stageSelect = { select: { id: true, name: true, kind: true, color: true, probability: true, position: true, key: true } } as const;

const rowInclude = {
  stage: stageSelect,
  assignee: { select: { id: true, name: true } },
  contact: { select: { id: true, firstName: true, lastName: true, companyName: true, phone: true, email: true } },
} satisfies Prisma.CrmDealInclude;

type DealRow = Prisma.CrmDealGetPayload<{ include: typeof rowInclude }>;

function shapeRow(d: DealRow) {
  const probability = d.probability ?? d.stage.probability;
  return {
    id: d.id,
    number: d.number,
    ref: dealRef(d.number),
    title: d.title,
    value: d.value,
    stageId: d.stageId,
    stage: d.stage,
    probability,
    probabilityOverride: d.probability,
    weighted: Math.round((d.value * probability) / 100),
    position: d.position,
    expectedCloseDate: d.expectedCloseDate,
    assignee: d.assignee,
    contact: d.contact ? { id: d.contact.id, name: fullName(d.contact), companyName: d.contact.companyName, phone: d.contact.phone, email: d.contact.email } : null,
    companyName: d.companyName,
    source: d.source,
    nextStep: d.nextStep,
    nextActionAt: d.nextActionAt,
    wonAt: d.wonAt,
    lostAt: d.lostAt,
    lostReason: d.lostReason,
    lostReasonCode: d.lostReasonCode,
    stageChangedAt: d.stageChangedAt,
    // The AI lead score (C6); only meaningful while the deal is open.
    aiScore: d.stage.kind === CrmStageKind.OPEN ? d.aiScore : null,
    aiScoreReason: d.stage.kind === CrmStageKind.OPEN ? d.aiScoreReason : null,
    aiScoredAt: d.stage.kind === CrmStageKind.OPEN ? d.aiScoredAt : null,
    createdAt: d.createdAt,
    updatedAt: d.updatedAt,
  };
}

export type DealView = ReturnType<typeof shapeRow>;

// ── Query ──────────────────────────────────────────────────────────────────

export interface DealQuery {
  q?: string;
  stageIds?: string[];
  status?: 'open' | 'won' | 'lost' | 'all';
  assigneeId?: string; // member id or 'none'
  contactId?: string;
  closing?: 'overdue' | 'thisMonth' | 'nextMonth' | 'none';
  valueMin?: number;
  valueMax?: number;
  sort?: 'updated' | 'created' | 'value' | 'close' | 'title' | 'number' | 'nextAction' | 'score';
  dir?: 'asc' | 'desc';
}

const IST_MS = 330 * 60 * 1000;

/** First instant of the Indian calendar month `offset` months from now's. */
function istMonthStart(now: Date, offset = 0) {
  const s = new Date(now.getTime() + IST_MS);
  return new Date(Date.UTC(s.getUTCFullYear(), s.getUTCMonth() + offset, 1) - IST_MS);
}

function istDayStart(now: Date) {
  const s = new Date(now.getTime() + IST_MS);
  return new Date(Date.UTC(s.getUTCFullYear(), s.getUTCMonth(), s.getUTCDate()) - IST_MS);
}

export function dealWhere(query: DealQuery, now = new Date()): Prisma.CrmDealWhereInput {
  const and: Prisma.CrmDealWhereInput[] = [{ deletedAt: null }];
  const q = query.q?.trim();
  if (q) {
    const num = /^(?:deal-?)?0*(\d{1,9})$/i.exec(q);
    for (const w of q.split(/\s+/).slice(0, 6)) {
      const like = { contains: w, mode: 'insensitive' as const };
      and.push({
        OR: [
          { title: like },
          { companyName: like },
          { nextStep: like },
          { contact: { OR: [{ firstName: like }, { lastName: like }, { companyName: like }] } },
          ...(num && q.split(/\s+/).length === 1 ? [{ number: Number(num[1]) }] : []),
        ],
      });
    }
  }
  if (query.stageIds?.length) and.push({ stageId: { in: query.stageIds } });
  if (query.status === 'open') and.push({ stage: { kind: CrmStageKind.OPEN } });
  if (query.status === 'won') and.push({ stage: { kind: CrmStageKind.WON } });
  if (query.status === 'lost') and.push({ stage: { kind: CrmStageKind.LOST } });
  if (query.assigneeId) and.push({ assigneeId: query.assigneeId === 'none' ? null : query.assigneeId });
  if (query.contactId) and.push({ OR: [{ contactId: query.contactId }, { contacts: { some: { contactId: query.contactId } } }] });
  if (query.closing === 'overdue') and.push({ expectedCloseDate: { lt: istDayStart(now) }, stage: { kind: CrmStageKind.OPEN } });
  if (query.closing === 'thisMonth') and.push({ expectedCloseDate: { gte: istMonthStart(now), lt: istMonthStart(now, 1) } });
  if (query.closing === 'nextMonth') and.push({ expectedCloseDate: { gte: istMonthStart(now, 1), lt: istMonthStart(now, 2) } });
  if (query.closing === 'none') and.push({ expectedCloseDate: null });
  if (query.valueMin !== undefined) and.push({ value: { gte: query.valueMin } });
  if (query.valueMax !== undefined) and.push({ value: { lte: query.valueMax } });
  return { AND: and };
}

function dealOrder(query: DealQuery): Prisma.CrmDealOrderByWithRelationInput[] {
  const asc = ['title', 'close', 'nextAction', 'number'].includes(query.sort ?? '');
  const dir = query.dir ?? (asc ? 'asc' : 'desc');
  const tail: Prisma.CrmDealOrderByWithRelationInput[] = [{ number: 'desc' }];
  switch (query.sort) {
    case 'value': return [{ value: dir }, ...tail];
    case 'score': return [{ aiScore: { sort: dir, nulls: 'last' } }, ...tail];
    case 'close': return [{ expectedCloseDate: { sort: dir, nulls: 'last' } }, ...tail];
    case 'nextAction': return [{ nextActionAt: { sort: dir, nulls: 'last' } }, ...tail];
    case 'title': return [{ title: dir }, ...tail];
    case 'number': return [{ number: dir }];
    case 'created': return [{ createdAt: dir }, ...tail];
    default: return [{ updatedAt: dir }, ...tail];
  }
}

/** Count, value and weighted value of a set of deals. */
function totalsOf(deals: { value: number; probability: number | null; stage: { probability: number } }[]) {
  let value = 0;
  let weighted = 0;
  for (const d of deals) {
    value += d.value;
    weighted += (d.value * (d.probability ?? d.stage.probability)) / 100;
  }
  return { count: deals.length, value, weighted: Math.round(weighted) };
}

const totalsSelect = { value: true, probability: true, stageId: true, stage: { select: { probability: true } } } as const;

export async function queryDeals(query: DealQuery, page = 1, limit = 25) {
  await ensureStages();
  const where = dealWhere(query);
  const [items, all] = await Promise.all([
    prismaUnscoped.crmDeal.findMany({ where, orderBy: dealOrder(query), skip: (page - 1) * limit, take: limit, include: rowInclude }),
    prismaUnscoped.crmDeal.findMany({ where, select: totalsSelect }),
  ]);
  const totals = totalsOf(all);
  return { items: items.map(shapeRow), total: totals.count, page, limit, pages: Math.max(1, Math.ceil(totals.count / limit)), totals };
}

const COLUMN_CAP = 200;

/**
 * The board: every stage, its matching deals in order, and its totals. Totals
 * count every matching deal, even past the cards a column shows, so a column
 * and the table with the same filters always agree.
 */
export async function board(query: DealQuery) {
  await ensureStages();
  const where = dealWhere(query);
  const [stages, deals] = await Promise.all([
    prismaUnscoped.crmStage.findMany({ orderBy: { position: 'asc' } }),
    prismaUnscoped.crmDeal.findMany({ where, orderBy: [{ position: 'asc' }, { number: 'asc' }], include: rowInclude, take: 5000 }),
  ]);
  const columns = stages.map((stage) => {
    const mine = deals.filter((d) => d.stageId === stage.id);
    return { stage, totals: totalsOf(mine), deals: mine.slice(0, COLUMN_CAP).map(shapeRow), truncated: mine.length > COLUMN_CAP };
  });
  return { columns, totals: totalsOf(deals) };
}

/** The headline figures above the board, for the whole pipeline. */
export async function summary(now = new Date()) {
  await ensureStages();
  const monthStart = istMonthStart(now);
  const [open, wonMonth, lostMonth, closed90] = await Promise.all([
    prismaUnscoped.crmDeal.findMany({ where: { deletedAt: null, stage: { kind: CrmStageKind.OPEN } }, select: totalsSelect }),
    prismaUnscoped.crmDeal.aggregate({ where: { deletedAt: null, stage: { kind: CrmStageKind.WON }, wonAt: { gte: monthStart } }, _count: { _all: true }, _sum: { value: true } }),
    prismaUnscoped.crmDeal.count({ where: { deletedAt: null, stage: { kind: CrmStageKind.LOST }, lostAt: { gte: monthStart } } }),
    prismaUnscoped.crmDeal.groupBy({
      by: ['stageId'],
      where: { deletedAt: null, OR: [{ wonAt: { gte: new Date(now.getTime() - 90 * 86_400_000) } }, { lostAt: { gte: new Date(now.getTime() - 90 * 86_400_000) } }] },
      _count: { _all: true },
    }),
  ]);
  const stages = await prismaUnscoped.crmStage.findMany({ select: { id: true, kind: true } });
  const won90 = closed90.filter((g) => stages.find((s) => s.id === g.stageId)?.kind === CrmStageKind.WON).reduce((a, g) => a + g._count._all, 0);
  const lost90 = closed90.filter((g) => stages.find((s) => s.id === g.stageId)?.kind === CrmStageKind.LOST).reduce((a, g) => a + g._count._all, 0);
  const o = totalsOf(open);
  return {
    open: o,
    wonThisMonth: { count: wonMonth._count._all, value: wonMonth._sum.value ?? 0 },
    lostThisMonth: lostMonth,
    winRate90: won90 + lost90 ? Math.round((won90 / (won90 + lost90)) * 100) : null,
  };
}

// ── One deal ───────────────────────────────────────────────────────────────

async function loadLive(id: string) {
  const d = await prismaUnscoped.crmDeal.findFirst({ where: { id, deletedAt: null }, include: { stage: true } });
  if (!d) throw new NotFoundError('Deal not found');
  return d;
}

export async function getDeal(id: string) {
  const d = await prismaUnscoped.crmDeal.findFirst({
    where: { id, deletedAt: null },
    include: {
      ...rowInclude,
      contacts: { orderBy: { addedAt: 'asc' }, include: { contact: { select: { id: true, firstName: true, lastName: true, companyName: true, phone: true, email: true, deletedAt: true } } } },
      tasks: { orderBy: [{ done: 'asc' }, { dueAt: { sort: 'asc', nulls: 'last' } }, { createdAt: 'asc' }], include: { assignee: { select: { id: true, name: true } } } },
    },
  });
  if (!d) throw new NotFoundError('Deal not found');
  const people = await prismaUnscoped.user.findMany({ where: { id: { in: [d.createdById, d.updatedById].filter((x): x is string => !!x) } }, select: { id: true, name: true } });
  const nameOf = (uid: string | null) => people.find((p) => p.id === uid)?.name ?? null;
  return {
    ...shapeRow(d),
    hostelAccount: await hostelAccountOf(d.tenantId),
    trialExtendedAt: d.trialExtendedAt,
    planInterest: d.planInterest,
    beds: d.beds,
    description: d.description,
    otherContacts: d.contacts.filter((c) => !c.contact.deletedAt).map((c) => ({ id: c.contact.id, name: fullName(c.contact), companyName: c.contact.companyName, phone: c.contact.phone, email: c.contact.email })),
    tasks: d.tasks.map((t) => ({ id: t.id, title: t.title, dueAt: t.dueAt, done: t.done, doneAt: t.doneAt, assignee: t.assignee })),
    createdByName: nameOf(d.createdById),
    updatedByName: nameOf(d.updatedById),
  };
}

async function assertContact(id: string) {
  const c = await prismaUnscoped.crmContact.findFirst({ where: { id, deletedAt: null }, select: { id: true, companyName: true } });
  if (!c) throw new BadRequestError('That contact does not exist or is in the bin.', 'INVALID_CONTACT');
  return c;
}

async function assertStage(id: string) {
  const s = await prismaUnscoped.crmStage.findUnique({ where: { id } });
  if (!s) throw new BadRequestError('That stage does not exist.', 'INVALID_STAGE');
  return s;
}

const clean = (v: string | null | undefined) => (v === undefined ? undefined : v?.trim() || null);

function scalarData(input: DealInput): Prisma.CrmDealUncheckedUpdateInput {
  const d: Prisma.CrmDealUncheckedUpdateInput = {};
  if (input.title !== undefined) d.title = input.title.trim();
  for (const k of ['companyName', 'source', 'planInterest', 'nextStep', 'description', 'lostReason'] as const) {
    if (input[k] !== undefined) d[k] = clean(input[k]);
  }
  for (const k of ['value', 'probability', 'expectedCloseDate', 'assigneeId', 'contactId', 'beds', 'nextActionAt'] as const) {
    if (input[k] !== undefined) (d as Record<string, unknown>)[k] = input[k];
  }
  return d;
}

/** Headline events show on the deal's main contact's timeline too. */
const withContact = (contactId: string | null) => (contactId ? { contactId } : {});

/** End of a column: one past the largest position in that stage. */
async function endOf(tx: Prisma.TransactionClient | typeof prismaUnscoped, stageId: string) {
  const top = await tx.crmDeal.aggregate({ where: { stageId, deletedAt: null }, _max: { position: true } });
  return (top._max.position ?? 0) + 1;
}

export async function createDeal(input: DealInput & { title: string }, actor: Actor) {
  await ensureStages();
  const stage = input.stageId
    ? await assertStage(input.stageId)
    : await prismaUnscoped.crmStage.findFirstOrThrow({ where: { kind: CrmStageKind.OPEN }, orderBy: { position: 'asc' } });
  const assigneeId = input.assigneeId === undefined ? actor.id : input.assigneeId;
  if (assigneeId) await assertMember(assigneeId);
  const contact = input.contactId ? await assertContact(input.contactId) : null;
  for (const cid of input.contactIds ?? []) await assertContact(cid);
  if (stage.kind === CrmStageKind.LOST && !input.lostReason?.trim()) throw new BadRequestError('Say why the deal was lost.', 'LOST_REASON_REQUIRED');

  const now = new Date();
  const deal = await prismaUnscoped.$transaction(async (tx) => {
    const d = await tx.crmDeal.create({
      data: {
        ...(scalarData(input) as Prisma.CrmDealUncheckedCreateInput),
        title: input.title.trim(),
        stageId: stage.id,
        position: await endOf(tx, stage.id),
        assigneeId,
        companyName: clean(input.companyName) ?? contact?.companyName ?? null,
        wonAt: stage.kind === CrmStageKind.WON ? now : null,
        lostAt: stage.kind === CrmStageKind.LOST ? now : null,
        lostReason: stage.kind === CrmStageKind.LOST ? clean(input.lostReason) : null,
        createdById: actor.id,
        updatedById: actor.id,
      },
    });
    const extra = (input.contactIds ?? []).filter((cid) => cid !== d.contactId);
    if (extra.length) await tx.crmDealContact.createMany({ data: extra.map((contactId) => ({ dealId: d.id, contactId })), skipDuplicates: true });
    await tx.crmActivity.create({
      data: { dealId: d.id, ...withContact(d.contactId), type: CrmActivityType.CREATED, meta: { ref: dealRef(d.number), title: d.title }, actorId: actor.id, actorName: actor.name },
    });
    return d;
  });
  notify({
    actor,
    text: `${actor.name} opened ${dealRef(deal.number)} · ${deal.title}${deal.value ? ` (${rupees(deal.value)})` : ''}${assigneeId && assigneeId !== actor.id ? ' and assigned it to you' : ''}`,
    url: crmUrl(`deals/${deal.id}`),
    about: [assigneeId],
  });
  return getDeal(deal.id);
}

/**
 * A free trial started (Sprint L2): the deal lands in the "Trial started"
 * stage, linked to the hostel account. The contact's open deal moves there
 * if it has one; otherwise a new deal is opened for the lead's owner.
 */
/** Sales check-in calls on trial days 1, 3 and 5, at 11 am India time (L5). */
async function planTrialCheckins(dealId: string, contactId: string, assigneeId: string | null, name: string, start: Date) {
  const day0 = new Date(start.getTime() + 330 * 60_000).toISOString().slice(0, 10);
  const workDays = new Set((await getCrmSettings()).workDays);
  // Day n at 11 am, or the next working day after it (a Sunday call waits for Monday).
  const at = (n: number) => {
    let t = Date.parse(`${day0}T11:00:00+05:30`) + n * 86_400_000;
    for (let i = 0; i < 7 && workDays.size && !workDays.has(new Date(t + 330 * 60_000).getUTCDay()); i++) t += 86_400_000;
    return new Date(t);
  };
  const exists = await prismaUnscoped.crmTask.count({ where: { dealId, kind: 'TRIAL_CHECKIN' } });
  if (exists) return;
  await prismaUnscoped.crmTask.createMany({
    data: [1, 3, 5].map((n) => ({ title: `Trial day ${n}: check in with ${name}`, dueAt: at(n), assigneeId, dealId, contactId, kind: 'TRIAL_CHECKIN' })),
  });
}

export async function openTrialDeal(p: { contactId: string; tenantId: string; title: string; companyName: string | null; beds: number; value: number; assigneeId: string | null; nextActionAt: Date | null; endsOn: string | null }) {
  const stage = await trialStage();
  const actorName = 'Free trial signup';
  const nextStep = `Trial check-in call${p.endsOn ? ` (trial ends ${p.endsOn})` : ''}`;
  const open = await prismaUnscoped.crmDeal.findFirst({
    where: { contactId: p.contactId, deletedAt: null, tenantId: null, stage: { kind: CrmStageKind.OPEN } },
    orderBy: { updatedAt: 'desc' },
    include: { stage: true },
  });
  if (open) {
    const moving = open.stageId !== stage.id;
    await prismaUnscoped.$transaction([
      prismaUnscoped.crmDeal.update({
        where: { id: open.id },
        data: {
          tenantId: p.tenantId,
          ...(moving ? { stageId: stage.id, stageChangedAt: new Date(), position: await endOf(prismaUnscoped, stage.id) } : {}),
          ...(open.value ? {} : { value: p.value }),
          ...(open.beds ? {} : { beds: p.beds }),
          ...(open.assigneeId ? {} : { assigneeId: p.assigneeId }),
          nextStep,
          nextActionAt: p.nextActionAt,
        },
      }),
      ...(moving
        ? [prismaUnscoped.crmActivity.create({ data: { dealId: open.id, ...withContact(open.contactId), type: CrmActivityType.STAGE_CHANGED, meta: { ref: dealRef(open.number), title: open.title, from: open.stage.name, to: stage.name }, actorName } })]
        : []),
    ]);
    await planTrialCheckins(open.id, p.contactId, open.assigneeId ?? p.assigneeId, p.companyName ?? p.title, new Date());
    return open.id;
  }
  const deal = await prismaUnscoped.$transaction(async (tx) => {
    const d = await tx.crmDeal.create({
      data: {
        title: p.title,
        value: p.value,
        stageId: stage.id,
        position: await endOf(tx, stage.id),
        assigneeId: p.assigneeId,
        contactId: p.contactId,
        companyName: p.companyName,
        source: 'Trial signup',
        beds: p.beds,
        nextStep,
        nextActionAt: p.nextActionAt,
        tenantId: p.tenantId,
      },
    });
    await tx.crmActivity.create({ data: { dealId: d.id, ...withContact(d.contactId), type: CrmActivityType.CREATED, meta: { ref: dealRef(d.number), title: d.title }, actorName } });
    return d;
  });
  await planTrialCheckins(deal.id, p.contactId, p.assigneeId, p.companyName ?? p.title, new Date());
  return deal.id;
}

const display = (v: unknown) => (v instanceof Date ? v.toISOString() : v ?? null);

export async function updateDeal(id: string, input: DealInput, actor: Actor) {
  const before = await loadLive(id);
  const { stageId: _s, contactIds, ...rest } = input;
  if (rest.assigneeId) await assertMember(rest.assigneeId);
  if (rest.contactId) await assertContact(rest.contactId);
  for (const cid of contactIds ?? []) await assertContact(cid);
  const moving = !!input.stageId && input.stageId !== before.stageId;
  if (moving) await moveDeal(id, { stageId: input.stageId!, lostReason: input.lostReason }, actor);
  const fresh = moving ? await loadLive(id) : before;
  // A reason belongs to a lost deal only; a move has already recorded it.
  if (rest.lostReason !== undefined) {
    if (moving || fresh.stage.kind !== CrmStageKind.LOST) delete rest.lostReason;
    else if (!rest.lostReason?.trim()) throw new BadRequestError('A lost deal keeps a reason.', 'LOST_REASON_REQUIRED');
  }

  const data = scalarData(rest);
  const changes: { field: string; label: string; from: unknown; to: unknown }[] = [];
  for (const [k, v] of Object.entries(data)) {
    const prev = (fresh as Record<string, unknown>)[k];
    if (JSON.stringify(display(prev)) === JSON.stringify(display(v))) continue;
    changes.push({ field: k, label: LABEL[k] ?? k, from: display(prev), to: display(v) });
  }
  // People by name, not by id.
  const ids = changes.filter((c) => c.field === 'assigneeId' || c.field === 'contactId').flatMap((c) => [c.from, c.to]).filter((x): x is string => typeof x === 'string');
  if (ids.length) {
    const [users, contacts] = await Promise.all([
      prismaUnscoped.user.findMany({ where: { id: { in: ids } }, select: { id: true, name: true } }),
      prismaUnscoped.crmContact.findMany({ where: { id: { in: ids } }, select: { id: true, firstName: true, lastName: true } }),
    ]);
    for (const c of changes) {
      if (c.field === 'assigneeId') {
        c.from = users.find((u) => u.id === c.from)?.name ?? null;
        c.to = users.find((u) => u.id === c.to)?.name ?? null;
      } else if (c.field === 'contactId') {
        const f = contacts.find((x) => x.id === c.from);
        const t = contacts.find((x) => x.id === c.to);
        c.from = f ? fullName(f) : null;
        c.to = t ? fullName(t) : null;
      }
    }
  }
  let contactsChanged = false;
  if (contactIds) {
    const now = await prismaUnscoped.crmDealContact.findMany({ where: { dealId: id }, select: { contactId: true } });
    const mainId = (data.contactId as string | null | undefined) ?? fresh.contactId;
    const want = [...new Set(contactIds.filter((c) => c !== mainId))];
    contactsChanged = JSON.stringify(now.map((c) => c.contactId).sort()) !== JSON.stringify([...want].sort());
    if (contactsChanged) {
      const names = await prismaUnscoped.crmContact.findMany({ where: { id: { in: [...want, ...now.map((c) => c.contactId)] } }, select: { id: true, firstName: true, lastName: true } });
      const n = (list: string[]) => list.map((cid) => names.find((x) => x.id === cid)).filter(Boolean).map((x) => fullName(x!));
      changes.push({ field: 'contacts', label: 'Other contacts', from: n(now.map((c) => c.contactId)), to: n(want) });
      await prismaUnscoped.$transaction([
        prismaUnscoped.crmDealContact.deleteMany({ where: { dealId: id } }),
        prismaUnscoped.crmDealContact.createMany({ data: want.map((contactId) => ({ dealId: id, contactId })) }),
      ]);
    }
  }
  if (!changes.length) return getDeal(id);
  await prismaUnscoped.$transaction([
    prismaUnscoped.crmDeal.update({ where: { id }, data: { ...data, updatedById: actor.id } }),
    prismaUnscoped.crmActivity.create({
      data: { dealId: id, type: CrmActivityType.UPDATED, changes: changes as Prisma.InputJsonValue, actorId: actor.id, actorName: actor.name },
    }),
  ]);
  const reassigned = rest.assigneeId !== undefined && rest.assigneeId !== fresh.assigneeId;
  notify({
    actor,
    text: reassigned && rest.assigneeId
      ? `${actor.name} assigned ${dealRef(fresh.number)} · ${fresh.title} to ${changes.find((c) => c.field === 'assigneeId')?.to ?? 'someone'}`
      : `${actor.name} updated ${dealRef(fresh.number)} · ${fresh.title}: ${describeChanges(changes.map((c) => (c.field === 'value' ? { ...c, from: typeof c.from === 'number' ? rupees(c.from) : c.from, to: typeof c.to === 'number' ? rupees(c.to) : c.to } : c)))}`,
    url: crmUrl(`deals/${id}`),
    about: [fresh.assigneeId, rest.assigneeId],
  });
  return getDeal(id);
}

/**
 * Put a deal in a stage, at a place in its column: between `afterId` (the
 * card above) and `beforeId` (the card below), or at the end.
 */
/** The next step that came with a move (L5): saved as part of the move, not as a separate edit. */
export async function setNextStep(id: string, next: { nextActionAt?: Date | null; nextStep?: string | null }, actor: Actor) {
  await prismaUnscoped.crmDeal.update({
    where: { id },
    data: { ...(next.nextActionAt !== undefined ? { nextActionAt: next.nextActionAt } : {}), ...(next.nextStep !== undefined ? { nextStep: next.nextStep?.trim() || null } : {}), updatedById: actor.id },
  });
  return getDeal(id);
}

export async function moveDeal(id: string, to: { stageId: string; afterId?: string | null; beforeId?: string | null; lostReason?: string | null; lostReasonCode?: LostReasonCode | null }, actor: Actor) {
  const deal = await loadLive(id);
  const stage = await assertStage(to.stageId);
  const changingStage = stage.id !== deal.stageId;
  // A code alone is enough: its label is the reason.
  if (to.lostReasonCode && !to.lostReason?.trim()) to = { ...to, lostReason: LOST_REASONS[to.lostReasonCode] };
  if (changingStage && stage.kind === CrmStageKind.LOST && !to.lostReason?.trim()) {
    throw new BadRequestError('Say why the deal was lost.', 'LOST_REASON_REQUIRED');
  }

  const neighbour = async (nid?: string | null) =>
    nid ? prismaUnscoped.crmDeal.findFirst({ where: { id: nid, stageId: stage.id, deletedAt: null, NOT: { id } }, select: { position: true } }) : null;
  const [above, below] = await Promise.all([neighbour(to.afterId), neighbour(to.beforeId)]);
  const position =
    above && below ? (above.position + below.position) / 2 :
    above ? above.position + 1 :
    below ? below.position - 1 :
    changingStage ? await endOf(prismaUnscoped, stage.id) : deal.position;

  const now = new Date();
  const ops: Prisma.PrismaPromise<unknown>[] = [];
  const data: Prisma.CrmDealUncheckedUpdateInput = { position, updatedById: actor.id };
  if (changingStage) {
    data.stageId = stage.id;
    data.stageChangedAt = now;
    const base = { dealId: id, ...withContact(deal.contactId), actorId: actor.id, actorName: actor.name };
    ops.push(prismaUnscoped.crmActivity.create({ data: { ...base, type: CrmActivityType.STAGE_CHANGED, meta: { ref: dealRef(deal.number), title: deal.title, from: deal.stage.name, to: stage.name } } }));
    if (stage.kind === CrmStageKind.WON) {
      Object.assign(data, { wonAt: now, lostAt: null, lostReason: null, lostReasonCode: null });
      ops.push(prismaUnscoped.crmActivity.create({ data: { ...base, type: CrmActivityType.WON, meta: { ref: dealRef(deal.number), title: deal.title, value: deal.value } } }));
    } else if (stage.kind === CrmStageKind.LOST) {
      Object.assign(data, { lostAt: now, wonAt: null, lostReason: to.lostReason!.trim(), lostReasonCode: to.lostReasonCode ?? 'OTHER' });
      ops.push(prismaUnscoped.crmActivity.create({ data: { ...base, type: CrmActivityType.LOST, body: to.lostReason!.trim(), meta: { ref: dealRef(deal.number), title: deal.title, reasonCode: to.lostReasonCode ?? 'OTHER' } } }));
    } else if (deal.stage.kind !== CrmStageKind.OPEN) {
      Object.assign(data, { wonAt: null, lostAt: null, lostReason: null, lostReasonCode: null });
      ops.push(prismaUnscoped.crmActivity.create({ data: { ...base, type: CrmActivityType.REOPENED, meta: { ref: dealRef(deal.number), title: deal.title } } }));
    }
  }
  await prismaUnscoped.$transaction([prismaUnscoped.crmDeal.update({ where: { id }, data }), ...ops]);
  if (changingStage) {
    const ref = `${dealRef(deal.number)} · ${deal.title}`;
    notify({
      actor,
      text:
        stage.kind === CrmStageKind.WON ? `${actor.name} won ${ref}${deal.value ? ` (${rupees(deal.value)})` : ''}` :
        stage.kind === CrmStageKind.LOST ? `${actor.name} lost ${ref}: ${to.lostReason!.trim()}` :
        deal.stage.kind !== CrmStageKind.OPEN ? `${actor.name} reopened ${ref} in ${stage.name}` :
        `${actor.name} moved ${ref} from ${deal.stage.name} to ${stage.name}`,
      url: crmUrl(`deals/${id}`),
      about: [deal.assigneeId],
    });
  }

  // A lost lead joins Nurture (L6) — except a wrong number or someone who was never a fit.
  if (changingStage && stage.kind === CrmStageKind.LOST && deal.contactId && to.lostReasonCode !== 'WRONG_NUMBER' && to.lostReasonCode !== 'NOT_A_FIT') {
    const c = await prismaUnscoped.crmContact.findFirst({ where: { id: deal.contactId, deletedAt: null }, select: { status: true } });
    if (c && c.status !== CrmContactStatus.CUSTOMER) await addToNurture(deal.contactId, actor);
  }

  // A won deal makes its main contact a customer.
  if (changingStage && stage.kind === CrmStageKind.WON && deal.contactId) {
    const c = await prismaUnscoped.crmContact.findFirst({ where: { id: deal.contactId, deletedAt: null }, select: { status: true } });
    if (c && c.status !== CrmContactStatus.CUSTOMER) {
      await prismaUnscoped.$transaction([
        prismaUnscoped.crmContact.update({ where: { id: deal.contactId }, data: { status: CrmContactStatus.CUSTOMER, updatedById: actor.id } }),
        prismaUnscoped.crmActivity.create({
          data: {
            contactId: deal.contactId,
            type: CrmActivityType.UPDATED,
            changes: [{ field: 'status', label: 'Status', from: c.status, to: CrmContactStatus.CUSTOMER }],
            meta: { reason: 'deal-won', ref: dealRef(deal.number) },
            actorId: actor.id,
            actorName: actor.name,
          },
        }),
      ]);
    }
  }
  return getDeal(id);
}

// ── Bin ────────────────────────────────────────────────────────────────────

export async function deleteDeal(id: string, actor: Actor) {
  const d = await loadLive(id);
  await prismaUnscoped.$transaction([
    prismaUnscoped.crmDeal.update({ where: { id }, data: { deletedAt: new Date(), deletedById: actor.id } }),
    prismaUnscoped.crmActivity.create({ data: { dealId: id, ...withContact(d.contactId), type: CrmActivityType.DELETED, meta: { ref: dealRef(d.number), title: d.title }, actorId: actor.id, actorName: actor.name } }),
  ]);
  notify({ actor, text: `${actor.name} moved ${dealRef(d.number)} · ${d.title} to the bin`, url: crmUrl('deals'), about: [d.assigneeId] });
}

export async function restoreDeal(id: string, actor: Actor) {
  const d = await prismaUnscoped.crmDeal.findFirst({ where: { id, deletedAt: { not: null } } });
  if (!d) throw new NotFoundError('That deal is not in the bin');
  await prismaUnscoped.$transaction([
    prismaUnscoped.crmDeal.update({ where: { id }, data: { deletedAt: null, deletedById: null, updatedById: actor.id, position: await endOf(prismaUnscoped, d.stageId) } }),
    prismaUnscoped.crmActivity.create({ data: { dealId: id, ...withContact(d.contactId), type: CrmActivityType.RESTORED, meta: { ref: dealRef(d.number), title: d.title }, actorId: actor.id, actorName: actor.name } }),
  ]);
  notify({ actor, text: `${actor.name} restored ${dealRef(d.number)} · ${d.title} from the bin`, url: crmUrl(`deals/${id}`), about: [d.assigneeId] });
  return getDeal(id);
}

export async function listDealBin(q: string | undefined, page = 1, limit = 25) {
  const where: Prisma.CrmDealWhereInput = {
    deletedAt: { not: null },
    ...(q?.trim() ? { OR: [{ title: { contains: q.trim(), mode: 'insensitive' } }, { companyName: { contains: q.trim(), mode: 'insensitive' } }] } : {}),
  };
  const [rows, total] = await Promise.all([
    prismaUnscoped.crmDeal.findMany({ where, orderBy: { deletedAt: 'desc' }, skip: (page - 1) * limit, take: limit, include: { stage: stageSelect } }),
    prismaUnscoped.crmDeal.count({ where }),
  ]);
  const people = await prismaUnscoped.user.findMany({ where: { id: { in: rows.map((r) => r.deletedById).filter((x): x is string => !!x) } }, select: { id: true, name: true } });
  return {
    items: rows.map((r) => ({
      id: r.id,
      ref: dealRef(r.number),
      title: r.title,
      value: r.value,
      companyName: r.companyName,
      stage: r.stage,
      deletedAt: r.deletedAt!,
      deletedByName: people.find((p) => p.id === r.deletedById)?.name ?? null,
      purgeAt: new Date(r.deletedAt!.getTime() + BIN_DAYS * 86_400_000),
    })),
    total,
    page,
    limit,
    pages: Math.max(1, Math.ceil(total / limit)),
  };
}

export async function purgeDealBin(now = new Date()) {
  const { count } = await prismaUnscoped.crmDeal.deleteMany({ where: { deletedAt: { lt: new Date(now.getTime() - BIN_DAYS * 86_400_000) } } });
  return count;
}

// ── Timeline, logged activity, tasks ───────────────────────────────────────

export async function dealTimeline(id: string, before?: Date, limit = 50) {
  await loadLive(id);
  const items = await prismaUnscoped.crmActivity.findMany({
    where: { dealId: id, ...(before ? { createdAt: { lt: before } } : {}) },
    orderBy: [{ createdAt: 'desc' }, { id: 'desc' }],
    take: limit + 1,
  });
  return { items: items.slice(0, limit), hasMore: items.length > limit };
}

export const LOGGABLE = ['NOTE', 'CALL', 'MEETING', 'EMAIL'] as const;

/** A note, or a call, meeting or email that happened, on the deal and its main contact. */
export async function logActivity(id: string, input: { type: (typeof LOGGABLE)[number]; body: string; at?: Date }, actor: Actor) {
  const d = await loadLive(id);
  if (input.at && input.at.getTime() > Date.now() + 60_000) throw new BadRequestError('That time is in the future.');
  const [a] = await prismaUnscoped.$transaction([
    prismaUnscoped.crmActivity.create({
      data: {
        dealId: id,
        ...withContact(d.contactId),
        type: CrmActivityType[input.type],
        body: input.body.trim(),
        meta: { ref: dealRef(d.number), title: d.title },
        actorId: actor.id,
        actorName: actor.name,
        ...(input.at ? { createdAt: input.at } : {}),
      },
    }),
    prismaUnscoped.crmDeal.update({ where: { id }, data: { updatedById: actor.id } }),
    ...(d.contactId && input.type !== 'NOTE'
      ? [prismaUnscoped.crmContact.updateMany({ where: { id: d.contactId, deletedAt: null }, data: { lastContactedAt: input.at ?? new Date() } })]
      : []),
  ]);
  // A call, meeting or email on the lead's deal is its first contact (L1).
  if (d.contactId && input.type !== 'NOTE') await markTouched(d.contactId, input.at ?? new Date());
  const what = { NOTE: 'added a note on', CALL: 'logged a call on', MEETING: 'logged a meeting on', EMAIL: 'logged an email on' }[input.type];
  notify({ actor, text: `${actor.name} ${what} ${dealRef(d.number)} · ${d.title}: "${input.body.trim().slice(0, 100)}${input.body.trim().length > 100 ? '…' : ''}"`, url: crmUrl(`deals/${id}`), about: [d.assigneeId] });
  return a;
}

const taskInclude = { assignee: { select: { id: true, name: true } }, deal: { select: { id: true, number: true, title: true } } } as const;

const shapeTask = (t: Prisma.CrmTaskGetPayload<{ include: typeof taskInclude }>) => ({
  id: t.id,
  title: t.title,
  dueAt: t.dueAt,
  done: t.done,
  doneAt: t.doneAt,
  assignee: t.assignee,
  deal: t.deal ? { id: t.deal.id, ref: dealRef(t.deal.number), title: t.deal.title } : null,
  createdAt: t.createdAt,
});

export async function createTask(dealId: string, input: { title: string; dueAt?: Date | null; assigneeId?: string | null }, actor: Actor) {
  const d = await loadLive(dealId);
  const assigneeId = input.assigneeId === undefined ? d.assigneeId ?? actor.id : input.assigneeId;
  if (assigneeId) await assertMember(assigneeId);
  const task = await prismaUnscoped.$transaction(async (tx) => {
    const t = await tx.crmTask.create({ data: { title: input.title.trim(), dueAt: input.dueAt ?? null, assigneeId, dealId, createdById: actor.id }, include: taskInclude });
    await tx.crmActivity.create({ data: { dealId, type: CrmActivityType.TASK_ADDED, meta: { taskId: t.id, title: t.title, dueAt: t.dueAt?.toISOString() ?? null, assignee: t.assignee?.name ?? null }, actorId: actor.id, actorName: actor.name } });
    return t;
  });
  notify({
    actor,
    text: `${actor.name} gave ${task.assignee?.id === d.assigneeId || !task.assignee ? 'a' : 'you a'} task on ${dealRef(d.number)}: ${task.title}${task.dueAt ? ` (due ${fmtIst(task.dueAt)})` : ''}`,
    url: crmUrl(`deals/${dealId}`),
    about: [task.assigneeId, d.assigneeId],
  });
  return shapeTask(task);
}

async function loadTask(id: string) {
  const t = await prismaUnscoped.crmTask.findFirst({ where: { id, OR: [{ dealId: null }, { deal: { deletedAt: null } }] }, include: taskInclude });
  if (!t) throw new NotFoundError('Task not found');
  return t;
}

export async function updateTask(id: string, input: { title?: string; dueAt?: Date | null; assigneeId?: string | null; done?: boolean }, actor: Actor) {
  const t = await loadTask(id);
  if (input.assigneeId) await assertMember(input.assigneeId);
  const finishing = input.done === true && !t.done;
  const updated = await prismaUnscoped.$transaction(async (tx) => {
    const u = await tx.crmTask.update({
      where: { id },
      data: {
        ...(input.title !== undefined ? { title: input.title.trim() } : {}),
        ...(input.dueAt !== undefined ? { dueAt: input.dueAt } : {}),
        ...(input.assigneeId !== undefined ? { assigneeId: input.assigneeId } : {}),
        ...(input.done !== undefined ? { done: input.done, doneAt: input.done ? new Date() : null } : {}),
      },
      include: taskInclude,
    });
    if (finishing && (t.dealId || t.contactId)) {
      await tx.crmActivity.create({ data: { dealId: t.dealId, contactId: t.contactId, type: CrmActivityType.TASK_DONE, meta: { taskId: id, title: u.title }, actorId: actor.id, actorName: actor.name } });
    }
    return u;
  });
  const where = updated.deal ? ` on ${dealRef(updated.deal.number)}` : '';
  if (input.assigneeId && input.assigneeId !== t.assigneeId) {
    notify({ actor, text: `${actor.name} gave you the task "${updated.title}"${where}${updated.dueAt ? ` (due ${fmtIst(updated.dueAt)})` : ''}`, url: updated.deal ? crmUrl(`deals/${updated.deal.id}`) : null, about: [input.assigneeId] });
  } else if (finishing && t.dealId) {
    const deal = await prismaUnscoped.crmDeal.findUnique({ where: { id: t.dealId }, select: { assigneeId: true } });
    notify({ actor, text: `${actor.name} finished "${updated.title}"${where}`, url: crmUrl(`deals/${t.dealId}`), about: [deal?.assigneeId, t.createdById] });
  }
  return shapeTask(updated);
}

export async function deleteTask(id: string) {
  await loadTask(id);
  await prismaUnscoped.crmTask.delete({ where: { id } });
}

/** Open tasks, soonest first: someone's, or everyone's. */
export async function listTasks(filter: { assigneeId?: string; open?: boolean }) {
  const rows = await prismaUnscoped.crmTask.findMany({
    where: {
      ...(filter.assigneeId ? { assigneeId: filter.assigneeId } : {}),
      ...(filter.open ? { done: false } : {}),
      OR: [{ dealId: null }, { deal: { deletedAt: null } }],
    },
    orderBy: [{ done: 'asc' }, { dueAt: { sort: 'asc', nulls: 'last' } }, { createdAt: 'asc' }],
    take: 200,
    include: taskInclude,
  });
  return rows.map(shapeTask);
}
