import { ZodError } from 'zod';
import { INDIAN_STATES } from '../../lib/india';
import { CrmActivityType, CrmContactStatus, CrmLeadGrade, CrmPropertyType, Prisma, Role } from '@prisma/client';
import { prismaUnscoped } from '../../lib/prisma';
import { env, publicWebUrl } from '../../config/env';
import { BadRequestError, NotFoundError } from '../../lib/errors';
import type { Actor } from './crm-users.service';
import { addMembers, removeMembers } from './crm-lists.service';
import { notify } from './crm-notify';
import { crmUrl } from './crm-mail';
import { createHmac, timingSafeEqual } from 'node:crypto';

/**
 * CRM contacts: the leads and customers the platform team sells HostelCare to.
 *
 * One shared workspace — every CRM member sees and edits every contact; each
 * keeps an owner, and who created and last changed it. Deleting moves a
 * contact to the bin for 30 days (see crm-jobs). Every change lands on the
 * contact's timeline as a CrmActivity, with field-level before and after.
 *
 * Platform-level: unscoped client throughout, reachable only behind
 * requireCrmAccess.
 */

export const BIN_DAYS = 30;

export const CONTACT_STATUSES = Object.values(CrmContactStatus);
export const PROPERTY_TYPES = Object.values(CrmPropertyType);

export const STATUS_LABEL: Record<CrmContactStatus, string> = {
  NEW: 'New',
  CONTACTED: 'Contacted',
  QUALIFIED: 'Qualified',
  CUSTOMER: 'Customer',
  LOST: 'Lost',
};

export const PROPERTY_TYPE_LABEL: Record<CrmPropertyType, string> = {
  HOSTEL: 'Hostel',
  PG: 'PG',
  DORMITORY: 'Dormitory',
  UNIVERSITY: 'University',
  COLIVING: 'Co-living',
  OTHER: 'Other',
};

/** Every editable field, as the API takes it. Absent = leave alone; null = clear. */
export interface ContactInput {
  firstName?: string;
  lastName?: string | null;
  email?: string | null;
  phone?: string | null;
  whatsapp?: string | null;
  designation?: string | null;
  companyName?: string | null;
  website?: string | null;
  linkedinUrl?: string | null;
  city?: string | null;
  state?: string | null;
  country?: string | null;
  address?: string | null;
  propertyType?: CrmPropertyType | null;
  approxBeds?: number | null;
  status?: CrmContactStatus;
  source?: string | null;
  tags?: string[];
  about?: string | null;
  ownerId?: string | null;
  lastContactedAt?: Date | null;
  nextFollowUpAt?: Date | null;
}

export const FIELD_LABEL: Record<keyof ContactInput, string> = {
  firstName: 'First name',
  lastName: 'Last name',
  email: 'Email',
  phone: 'Phone',
  whatsapp: 'WhatsApp',
  designation: 'Designation',
  companyName: 'Company',
  website: 'Website',
  linkedinUrl: 'LinkedIn',
  city: 'City',
  state: 'State',
  country: 'Country',
  address: 'Address',
  propertyType: 'Property type',
  approxBeds: 'Approx. beds',
  status: 'Status',
  source: 'Source',
  tags: 'Tags',
  about: 'About',
  ownerId: 'Owner',
  lastContactedAt: 'Last contacted',
  nextFollowUpAt: 'Next follow-up',
};

// ── Normalising ────────────────────────────────────────────────────────────

export const emailKeyOf = (email: string | null | undefined) => (email?.trim() ? email.trim().toLowerCase() : null);

/** The last ten digits, so +91 98765 43210 and 098765-43210 match. */
export function phoneKeyOf(phone: string | null | undefined): string | null {
  const digits = (phone ?? '').replace(/\D/g, '');
  if (digits.length < 7) return null;
  return digits.slice(-10);
}

/** Trimmed, de-duplicated regardless of case, keeping the first spelling. */
export function cleanTags(tags: string[]): string[] {
  const seen = new Set<string>();
  const out: string[] = [];
  for (const t of tags) {
    const v = t.trim().replace(/\s+/g, ' ');
    if (!v || seen.has(v.toLowerCase())) continue;
    seen.add(v.toLowerCase());
    out.push(v);
  }
  return out;
}

/** "example.com" → "https://example.com"; anything else as typed. */
export function cleanUrl(url: string | null | undefined): string | null {
  const v = url?.trim();
  if (!v) return null;
  return /^https?:\/\//i.test(v) ? v : `https://${v}`;
}

/** The owner must be someone who can open the CRM and is switched on. */
export async function assertMember(userId: string) {
  const u = await prismaUnscoped.user.findFirst({
    where: { id: userId, role: { in: [Role.CRM_USER, Role.SUPER_ADMIN] }, deactivatedAt: null },
    select: { id: true },
  });
  if (!u) throw new BadRequestError('The owner must be an active CRM member.', 'INVALID_OWNER');
}

/**
 * Rules that depend on the contact's country (10 Oct 2026): in India (the
 * default) a phone or WhatsApp number has ten digits after any +91 or 0, and
 * the state must be one of the states and union territories — matched
 * regardless of case and saved in its proper spelling. Only fields being set
 * are checked, so a stored older value never blocks an unrelated edit.
 * Raised as field errors, like the schema's own.
 */
export function checkByCountry(input: ContactInput, storedCountry: string | null | undefined) {
  const country = (input.country !== undefined ? input.country : storedCountry)?.trim() || 'India';
  if (country.toLowerCase() !== 'india') return;
  const issues: { code: 'custom'; path: string[]; message: string }[] = [];
  for (const [k, label] of [['phone', 'Phone'], ['whatsapp', 'WhatsApp']] as const) {
    const v = input[k];
    if (!v) continue;
    const d = v.replace(/\D/g, '');
    const local = d.length === 12 && d.startsWith('91') ? d.slice(2) : d.length === 11 && d.startsWith('0') ? d.slice(1) : d;
    if (!/^[1-9]\d{9}$/.test(local)) issues.push({ code: 'custom', path: [k], message: `${label}: enter a 10-digit Indian number (a +91 or 0 in front is fine)` });
  }
  if (input.state) {
    const match = (INDIAN_STATES as readonly string[]).find((x) => x.toLowerCase() === input.state!.trim().toLowerCase());
    if (match) input.state = match;
    else issues.push({ code: 'custom', path: ['state'], message: 'Pick a state or union territory of India from the list' });
  }
  if (issues.length) throw new ZodError(issues);
}

/** Turn API input into column values, deriving the match keys. */
function toData(input: ContactInput): Prisma.CrmContactUncheckedUpdateInput {
  const d: Prisma.CrmContactUncheckedUpdateInput = {};
  for (const [k, v] of Object.entries(input) as [keyof ContactInput, unknown][]) {
    if (v === undefined) continue;
    if (k === 'tags') d.tags = cleanTags(v as string[]);
    else if (k === 'website' || k === 'linkedinUrl') d[k] = cleanUrl(v as string | null);
    else (d as Record<string, unknown>)[k] = typeof v === 'string' ? v.trim() || null : v;
  }
  if (input.firstName !== undefined) d.firstName = input.firstName.trim();
  if (input.email !== undefined) {
    d.email = input.email?.trim() ? input.email.trim().toLowerCase() : null;
    d.emailKey = emailKeyOf(input.email);
  }
  if (input.phone !== undefined) d.phoneKey = phoneKeyOf(input.phone);
  return d;
}

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

const ownerSelect = { select: { id: true, name: true } } as const;

const rowSelect = {
  id: true,
  firstName: true,
  lastName: true,
  email: true,
  phone: true,
  designation: true,
  companyName: true,
  city: true,
  state: true,
  status: true,
  source: true,
  propertyType: true,
  approxBeds: true,
  tags: true,
  owner: ownerSelect,
  nextFollowUpAt: true,
  lastContactedAt: true,
  leadGrade: true,
  // L6: the call list shows who said stop, and sorts by the AI score.
  optedOutAt: true,
  leadScore: true,
  leadDueAt: true,
  firstTouchAt: true,
  latestSource: true,
  createdAt: true,
  updatedAt: true,
} satisfies Prisma.CrmContactSelect;

export type ContactRow = Prisma.CrmContactGetPayload<{ select: typeof rowSelect }>;

export const fullName = (c: { firstName: string; lastName?: string | null }) => [c.firstName, c.lastName].filter(Boolean).join(' ');

const shapeRow = (c: ContactRow) => ({ ...c, name: fullName(c) });

// ── Query: search, quick filters and AND/OR conditions ─────────────────────

const TEXT_FIELDS = ['firstName', 'lastName', 'email', 'phone', 'companyName', 'designation', 'city', 'state', 'country', 'source'] as const;
const DATE_FIELDS = ['createdAt', 'updatedAt', 'nextFollowUpAt', 'lastContactedAt'] as const;
export const CONDITION_FIELDS = [...TEXT_FIELDS, ...DATE_FIELDS, 'status', 'propertyType', 'approxBeds', 'tags', 'ownerId', 'listId'] as const;
export const CONDITION_OPS = ['eq', 'ne', 'contains', 'notContains', 'in', 'notIn', 'gt', 'gte', 'lt', 'lte', 'between', 'empty', 'notEmpty', 'has', 'missing'] as const;

export type ConditionField = (typeof CONDITION_FIELDS)[number];
export type ConditionOp = (typeof CONDITION_OPS)[number];
export interface Condition {
  field: ConditionField;
  op: ConditionOp;
  value?: unknown;
}

export interface ContactQuery {
  q?: string;
  status?: CrmContactStatus[];
  ownerId?: string; // a member id, or 'none'
  source?: string;
  propertyType?: CrmPropertyType;
  tag?: string;
  listId?: string;
  followUp?: 'overdue' | 'today' | 'week' | 'none';
  /** New leads still waiting for their first call or message (L1). */
  waiting?: boolean;
  grade?: CrmLeadGrade;
  conditions?: Condition[];
  combine?: 'and' | 'or';
  sort?: 'updated' | 'created' | 'name' | 'company' | 'followUp' | 'city';
  dir?: 'asc' | 'desc';
}

const IST_MS = 330 * 60 * 1000;

/** Midnight in India for the day `d` falls on, as a UTC instant. */
function istDayStart(d: Date) {
  const shifted = new Date(d.getTime() + IST_MS);
  return new Date(Date.UTC(shifted.getUTCFullYear(), shifted.getUTCMonth(), shifted.getUTCDate()) - IST_MS);
}

const bad = (c: Condition, why: string) => new BadRequestError(`Filter on ${c.field}: ${why}`, 'INVALID_FILTER');

function asDate(c: Condition, v: unknown): Date {
  const d = typeof v === 'string' || typeof v === 'number' ? new Date(v) : null;
  if (!d || Number.isNaN(d.getTime())) throw bad(c, 'expects a date');
  return d;
}

function asNumber(c: Condition, v: unknown): number {
  const n = typeof v === 'number' ? v : typeof v === 'string' && v.trim() !== '' ? Number(v) : NaN;
  if (!Number.isFinite(n)) throw bad(c, 'expects a number');
  return n;
}

function asString(c: Condition, v: unknown): string {
  if (typeof v !== 'string' || !v.trim()) throw bad(c, 'expects a value');
  return v.trim().slice(0, 200);
}

function asList<T extends string>(c: Condition, v: unknown, allowed: readonly T[]): T[] {
  const arr = Array.isArray(v) ? v : [v];
  if (!arr.length || arr.some((x) => !allowed.includes(x as T))) throw bad(c, `expects one of ${allowed.join(', ')}`);
  return arr as T[];
}

function conditionWhere(c: Condition): Prisma.CrmContactWhereInput {
  const f = c.field;
  const empty = c.op === 'empty';
  if ((TEXT_FIELDS as readonly string[]).includes(f)) {
    const k = f as (typeof TEXT_FIELDS)[number];
    switch (c.op) {
      case 'eq': return { [k]: { equals: asString(c, c.value), mode: 'insensitive' } };
      case 'ne': return { NOT: { [k]: { equals: asString(c, c.value), mode: 'insensitive' } } };
      case 'contains': return { [k]: { contains: asString(c, c.value), mode: 'insensitive' } };
      case 'notContains': return { NOT: { [k]: { contains: asString(c, c.value), mode: 'insensitive' } } };
      case 'empty': case 'notEmpty': {
        const blank: Prisma.CrmContactWhereInput = { OR: [{ [k]: null }, { [k]: '' }] };
        return empty ? blank : { NOT: blank };
      }
    }
  }
  if ((DATE_FIELDS as readonly string[]).includes(f)) {
    const k = f as (typeof DATE_FIELDS)[number];
    switch (c.op) {
      case 'lt': return { [k]: { lt: asDate(c, c.value) } };
      case 'gt': return { [k]: { gt: asDate(c, c.value) } };
      case 'between': {
        const [a, b] = Array.isArray(c.value) ? c.value : [];
        return { [k]: { gte: asDate(c, a), lte: asDate(c, b) } };
      }
      case 'empty': return { [k]: null };
      case 'notEmpty': return { [k]: { not: null } };
    }
  }
  if (f === 'status' || f === 'propertyType') {
    const allowed = (f === 'status' ? CONTACT_STATUSES : PROPERTY_TYPES) as string[];
    switch (c.op) {
      case 'eq': case 'in': return { [f]: { in: asList(c, c.value, allowed) } };
      case 'ne': case 'notIn': return { NOT: { [f]: { in: asList(c, c.value, allowed) } } };
      case 'empty': return { [f]: null };
      case 'notEmpty': return { [f]: { not: null } };
    }
  }
  if (f === 'approxBeds') {
    switch (c.op) {
      case 'eq': return { approxBeds: asNumber(c, c.value) };
      case 'ne': return { NOT: { approxBeds: asNumber(c, c.value) } };
      case 'gt': return { approxBeds: { gt: asNumber(c, c.value) } };
      case 'gte': return { approxBeds: { gte: asNumber(c, c.value) } };
      case 'lt': return { approxBeds: { lt: asNumber(c, c.value) } };
      case 'lte': return { approxBeds: { lte: asNumber(c, c.value) } };
      case 'between': {
        const [a, b] = Array.isArray(c.value) ? c.value : [];
        return { approxBeds: { gte: asNumber(c, a), lte: asNumber(c, b) } };
      }
      case 'empty': return { approxBeds: null };
      case 'notEmpty': return { approxBeds: { not: null } };
    }
  }
  if (f === 'tags') {
    switch (c.op) {
      case 'has': return { tags: { has: asString(c, c.value) } };
      case 'missing': return { NOT: { tags: { has: asString(c, c.value) } } };
      case 'empty': return { tags: { isEmpty: true } };
      case 'notEmpty': return { NOT: { tags: { isEmpty: true } } };
    }
  }
  if (f === 'ownerId') {
    switch (c.op) {
      case 'eq': return { ownerId: asString(c, c.value) };
      case 'ne': return { NOT: { ownerId: asString(c, c.value) } };
      case 'empty': return { ownerId: null };
      case 'notEmpty': return { ownerId: { not: null } };
    }
  }
  if (f === 'listId') {
    switch (c.op) {
      case 'eq': case 'has': return { lists: { some: { listId: asString(c, c.value) } } };
      case 'ne': case 'missing': return { lists: { none: { listId: asString(c, c.value) } } };
    }
  }
  throw bad(c, `"${c.op}" does not apply`);
}

/** Each word must match some field, so "ravi indore" finds Ravi in Indore. */
function searchWhere(q: string): Prisma.CrmContactWhereInput[] {
  return q
    .trim()
    .split(/\s+/)
    .filter(Boolean)
    .slice(0, 6)
    .map((w) => {
      const digits = w.replace(/\D/g, '');
      const like = { contains: w, mode: 'insensitive' as const };
      return {
        OR: [
          { firstName: like },
          { lastName: like },
          { email: like },
          { companyName: like },
          { designation: like },
          { city: like },
          { tags: { has: w } },
          ...(digits.length >= 3 ? [{ phone: { contains: digits } }, { phoneKey: { contains: digits } }] : []),
        ],
      };
    });
}

export function buildWhere(query: ContactQuery, now = new Date()): Prisma.CrmContactWhereInput {
  const and: Prisma.CrmContactWhereInput[] = [{ deletedAt: null }];
  if (query.q?.trim()) and.push(...searchWhere(query.q));
  if (query.status?.length) and.push({ status: { in: query.status } });
  if (query.ownerId) and.push({ ownerId: query.ownerId === 'none' ? null : query.ownerId });
  if (query.source) and.push({ source: { equals: query.source, mode: 'insensitive' } });
  if (query.propertyType) and.push({ propertyType: query.propertyType });
  if (query.tag) and.push({ tags: { has: query.tag } });
  if (query.listId) and.push({ lists: { some: { listId: query.listId } } });
  if (query.waiting) and.push(WAITING);
  if (query.grade) and.push({ leadGrade: query.grade });
  if (query.followUp) {
    const today = istDayStart(now);
    const tomorrow = new Date(today.getTime() + 86_400_000);
    if (query.followUp === 'overdue') and.push({ nextFollowUpAt: { lt: now } });
    else if (query.followUp === 'today') and.push({ nextFollowUpAt: { gte: today, lt: tomorrow } });
    else if (query.followUp === 'week') and.push({ nextFollowUpAt: { gte: now, lt: new Date(now.getTime() + 7 * 86_400_000) } });
    else and.push({ nextFollowUpAt: null });
  }
  if (query.conditions?.length) {
    const parts = query.conditions.map(conditionWhere);
    and.push(query.combine === 'or' ? { OR: parts } : { AND: parts });
  }
  return { AND: and };
}

/** A new lead nobody has called or written to yet. */
const WAITING: Prisma.CrmContactWhereInput = { status: CrmContactStatus.NEW, firstTouchAt: null, leadDueAt: { not: null } };

function orderBy(query: ContactQuery): Prisma.CrmContactOrderByWithRelationInput[] {
  // Waiting leads: the one due first, first.
  // The call list (L6): hot leads first, then the AI's best bets, then whoever is due soonest.
  if (query.waiting && !query.sort) return [{ leadGrade: 'asc' }, { leadScore: { sort: 'desc', nulls: 'last' } }, { leadDueAt: 'asc' }, { id: 'asc' }];
  const dir = query.dir ?? (query.sort === 'name' || query.sort === 'company' || query.sort === 'city' || query.sort === 'followUp' ? 'asc' : 'desc');
  const tail: Prisma.CrmContactOrderByWithRelationInput[] = [{ id: 'asc' }];
  switch (query.sort) {
    case 'name': return [{ firstName: dir }, { lastName: { sort: dir, nulls: 'last' } }, ...tail];
    case 'company': return [{ companyName: { sort: dir, nulls: 'last' } }, ...tail];
    case 'city': return [{ city: { sort: dir, nulls: 'last' } }, ...tail];
    case 'followUp': return [{ nextFollowUpAt: { sort: dir, nulls: 'last' } }, ...tail];
    case 'created': return [{ createdAt: dir }, ...tail];
    default: return [{ updatedAt: dir }, ...tail];
  }
}

export async function queryContacts(query: ContactQuery, page = 1, limit = 25) {
  const where = buildWhere(query);
  const [items, total] = await Promise.all([
    prismaUnscoped.crmContact.findMany({ where, orderBy: orderBy(query), skip: (page - 1) * limit, take: limit, select: rowSelect }),
    prismaUnscoped.crmContact.count({ where }),
  ]);
  return { items: items.map(shapeRow), total, page, limit, pages: Math.max(1, Math.ceil(total / limit)) };
}

/** All matching rows, for an export. Capped so one request cannot pull the world. */
export async function allMatching(query: ContactQuery, cap = 10_000) {
  return prismaUnscoped.crmContact.findMany({
    where: buildWhere(query),
    orderBy: orderBy(query),
    take: cap,
    select: { ...rowSelect, whatsapp: true, website: true, linkedinUrl: true, country: true, address: true, about: true },
  });
}

/** What the filter bar needs: counts per status, the tags and cities in use, the sources on offer. */
export async function facets() {
  const [byStatus, tags, cities, settings, waiting, late] = await Promise.all([
    prismaUnscoped.crmContact.groupBy({ by: ['status'], where: { deletedAt: null }, _count: { _all: true } }),
    prismaUnscoped.$queryRaw<{ tag: string }[]>`SELECT DISTINCT unnest(tags) AS tag FROM "CrmContact" WHERE "deletedAt" IS NULL ORDER BY 1 LIMIT 300`,
    prismaUnscoped.$queryRaw<{ city: string }[]>`SELECT city FROM "CrmContact" WHERE "deletedAt" IS NULL AND city IS NOT NULL AND city <> '' GROUP BY city ORDER BY count(*) DESC, city LIMIT 100`,
    prismaUnscoped.crmSettings.findUnique({ where: { id: 'singleton' }, select: { contactSources: true } }),
    prismaUnscoped.crmContact.count({ where: { deletedAt: null, ...WAITING } }),
    prismaUnscoped.crmContact.count({ where: { deletedAt: null, ...WAITING, leadDueAt: { lt: new Date() } } }),
  ]);
  const statusCounts = Object.fromEntries(CONTACT_STATUSES.map((s) => [s, 0])) as Record<CrmContactStatus, number>;
  for (const r of byStatus) statusCounts[r.status] = r._count._all;
  return {
    statusCounts,
    total: Object.values(statusCounts).reduce((a, b) => a + b, 0),
    tags: tags.map((t) => t.tag),
    cities: cities.map((c) => c.city),
    waiting,
    waitingLate: late,
    sources: settings?.contactSources ?? ['Website', 'Referral', 'Cold call', 'Event', 'Social media', 'Advertisement', 'Partner', 'Other'],
  };
}

/** Contacts that share this email or phone — a warning while typing, never a refusal. */
export async function findDuplicates(email: string | undefined, phone: string | undefined, excludeId?: string) {
  const ek = emailKeyOf(email);
  const pk = phoneKeyOf(phone);
  if (!ek && !pk) return [];
  const rows = await prismaUnscoped.crmContact.findMany({
    where: {
      OR: [...(ek ? [{ emailKey: ek }] : []), ...(pk ? [{ phoneKey: pk }] : [])],
      ...(excludeId ? { id: { not: excludeId } } : {}),
    },
    orderBy: { updatedAt: 'desc' },
    take: 5,
    select: { id: true, firstName: true, lastName: true, email: true, phone: true, companyName: true, deletedAt: true, emailKey: true, phoneKey: true },
  });
  return rows.map((r) => ({
    id: r.id,
    name: fullName(r),
    email: r.email,
    phone: r.phone,
    companyName: r.companyName,
    inBin: !!r.deletedAt,
    matchedOn: [...(ek && r.emailKey === ek ? ['email'] : []), ...(pk && r.phoneKey === pk ? ['phone'] : [])],
  }));
}

// ── One contact ────────────────────────────────────────────────────────────

async function loadLive(id: string) {
  const c = await prismaUnscoped.crmContact.findFirst({ where: { id, deletedAt: null } });
  if (!c) throw new NotFoundError('Contact not found');
  return c;
}

/**
 * The HostelCare account a contact or deal belongs to — set when they start
 * a free trial (Sprint L2) — with where its access stands.
 */
export async function hostelAccountOf(tenantId: string | null) {
  if (!tenantId) return null;
  const t = await prismaUnscoped.tenant.findUnique({ where: { id: tenantId }, select: { id: true, name: true, kind: true, status: true, accessKind: true, accessEndsOn: true } });
  if (!t) return null;
  return { id: t.id, name: t.name, kind: t.kind, status: t.status, accessKind: t.accessKind, endsOn: t.accessEndsOn ? t.accessEndsOn.toISOString().slice(0, 10) : null };
}

export async function getContact(id: string) {
  const c = await prismaUnscoped.crmContact.findFirst({
    where: { id, deletedAt: null },
    include: {
      owner: ownerSelect,
      lists: { orderBy: { addedAt: 'desc' }, select: { addedAt: true, list: { select: { id: true, name: true, color: true } } } },
    },
  });
  if (!c) throw new NotFoundError('Contact not found');
  const people = await prismaUnscoped.user.findMany({
    where: { id: { in: [c.createdById, c.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;
  const { emailKey: _e, phoneKey: _p, deletedAt: _d, deletedById: _db, lists, ...rest } = c;
  return {
    ...rest,
    name: fullName(c),
    hostelAccount: await hostelAccountOf(c.tenantId),
    lists: lists.map((l) => ({ ...l.list, addedAt: l.addedAt })),
    createdByName: nameOf(c.createdById),
    updatedByName: nameOf(c.updatedById),
  };
}

export async function createContact(input: ContactInput & { firstName: string }, actor: Actor) {
  checkByCountry(input, null);
  const ownerId = input.ownerId === undefined ? actor.id : input.ownerId;
  if (ownerId) await assertMember(ownerId);
  const data = toData({ ...input, ownerId }) as Prisma.CrmContactUncheckedCreateInput;
  const contact = await prismaUnscoped.$transaction(async (tx) => {
    const c = await tx.crmContact.create({ data: { ...data, firstName: input.firstName.trim(), createdById: actor.id, updatedById: actor.id } });
    await tx.crmActivity.create({ data: { contactId: c.id, type: CrmActivityType.CREATED, actorId: actor.id, actorName: actor.name } });
    return c;
  });
  notify({
    actor,
    text: `${actor.name} added ${fullName(contact)}${contact.companyName ? ` (${contact.companyName})` : ''}${ownerId && ownerId !== actor.id ? ' and made you the owner' : ''}`,
    url: crmUrl(`contacts/${contact.id}`),
    about: [ownerId],
  });
  return getContact(contact.id);
}

/** A value as the timeline shows it: dates as ISO, tags as a list, owners by name. */
function display(v: unknown): unknown {
  if (v instanceof Date) return v.toISOString();
  return v ?? null;
}

const same = (a: unknown, b: unknown) => JSON.stringify(display(a)) === JSON.stringify(display(b));

export async function updateContact(id: string, input: ContactInput, actor: Actor) {
  const before = await loadLive(id);
  checkByCountry(input, before.country);
  if (input.ownerId) await assertMember(input.ownerId);
  const data = toData(input);
  const changes: { field: string; label: string; from: unknown; to: unknown }[] = [];
  const ownerNames = new Map<string, string>();
  for (const key of Object.keys(input) as (keyof ContactInput)[]) {
    if (input[key] === undefined) continue;
    const next = (data as Record<string, unknown>)[key];
    const prev = (before as Record<string, unknown>)[key];
    if (same(prev, next)) continue;
    changes.push({ field: key, label: FIELD_LABEL[key], from: display(prev), to: display(next) });
    if (key === 'ownerId') for (const uid of [prev, next]) if (typeof uid === 'string') ownerNames.set(uid, '');
  }
  if (!changes.length) return getContact(id);
  if (ownerNames.size) {
    const people = await prismaUnscoped.user.findMany({ where: { id: { in: [...ownerNames.keys()] } }, select: { id: true, name: true } });
    for (const ch of changes) {
      if (ch.field !== 'ownerId') continue;
      ch.from = people.find((p) => p.id === ch.from)?.name ?? null;
      ch.to = people.find((p) => p.id === ch.to)?.name ?? null;
    }
  }
  await prismaUnscoped.$transaction([
    prismaUnscoped.crmContact.update({ where: { id }, data: { ...data, updatedById: actor.id } }),
    prismaUnscoped.crmActivity.create({
      data: { contactId: id, type: CrmActivityType.UPDATED, changes: changes as Prisma.InputJsonValue, actorId: actor.id, actorName: actor.name },
    }),
  ]);
  // Moving a lead on from New, or recording that they were contacted, is the first contact.
  if ((input.status && input.status !== CrmContactStatus.NEW && before.status === CrmContactStatus.NEW) || input.lastContactedAt) await markTouched(id);
  notify({ actor, text: `${actor.name} updated ${fullName(before)}: ${describeChanges(changes)}`, url: crmUrl(`contacts/${id}`), about: [before.ownerId, input.ownerId] });
  return getContact(id);
}

/** "Status: New → Qualified; Owner: Ravi → Priya" — the first few, for an alert. */
export function describeChanges(changes: { label: string; from: unknown; to: unknown; field: string }[]) {
  const show = (f: string, v: unknown) => {
    if (v === null || v === undefined || v === '') return 'empty';
    if (f === 'status') return STATUS_LABEL[v as CrmContactStatus] ?? String(v);
    if (Array.isArray(v)) return v.join(', ') || 'none';
    if (typeof v === 'string' && /^\d{4}-\d{2}-\d{2}T/.test(v)) return new Date(v).toLocaleString('en-IN', { timeZone: 'Asia/Kolkata', day: 'numeric', month: 'short', hour: 'numeric', minute: '2-digit' });
    const s = String(v);
    return s.length > 40 ? `${s.slice(0, 37)}…` : s;
  };
  const first = changes.slice(0, 3).map((c) => `${c.label}: ${show(c.field, c.from)} → ${show(c.field, c.to)}`);
  return first.join('; ') + (changes.length > 3 ? ` and ${changes.length - 3} more` : '');
}

/**
 * The first real contact after a lead came in (L1): a call or note, a status
 * change, a call logged on its deal. Only leads on a response clock are marked.
 */
export async function markTouched(contactIds: string | string[], at = new Date()) {
  const ids = Array.isArray(contactIds) ? contactIds : [contactIds];
  if (!ids.length) return;
  await prismaUnscoped.crmContact.updateMany({ where: { id: { in: ids }, firstTouchAt: null, leadDueAt: { not: null } }, data: { firstTouchAt: at } });
}

export async function addNote(id: string, body: string, actor: Actor, type: 'NOTE' | 'CALL' = 'NOTE') {
  await loadLive(id);
  const now = new Date();
  const [activity] = await prismaUnscoped.$transaction([
    prismaUnscoped.crmActivity.create({ data: { contactId: id, type: CrmActivityType[type], body: body.trim(), actorId: actor.id, actorName: actor.name } }),
    // A note is work on the contact: it moves it up the "recently updated" list.
    // A call is also the last time they were contacted.
    prismaUnscoped.crmContact.update({ where: { id }, data: { updatedById: actor.id, ...(type === 'CALL' ? { lastContactedAt: now } : {}) } }),
  ]);
  // A lead waiting for its first contact has now had it.
  await markTouched(id, now);
  const c = await prismaUnscoped.crmContact.findUnique({ where: { id }, select: { firstName: true, lastName: true, ownerId: true } });
  const what = type === 'CALL' ? 'logged a call with' : 'added a note on';
  if (c) notify({ actor, text: `${actor.name} ${what} ${fullName(c)}: "${body.trim().slice(0, 100)}${body.trim().length > 100 ? '…' : ''}"`, url: crmUrl(`contacts/${id}`), about: [c.ownerId] });
  return activity;
}

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

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

export async function deleteContacts(ids: string[], actor: Actor) {
  const live = await prismaUnscoped.crmContact.findMany({ where: { id: { in: ids }, deletedAt: null }, select: { id: true, firstName: true, lastName: true, ownerId: true } });
  if (!live.length) return 0;
  const now = new Date();
  await prismaUnscoped.$transaction([
    prismaUnscoped.crmContact.updateMany({ where: { id: { in: live.map((c) => c.id) } }, data: { deletedAt: now, deletedById: actor.id } }),
    prismaUnscoped.crmActivity.createMany({
      data: live.map((c) => ({ contactId: c.id, type: CrmActivityType.DELETED, actorId: actor.id, actorName: actor.name })),
    }),
  ]);
  notify({
    actor,
    text: live.length === 1 ? `${actor.name} moved ${fullName(live[0])} to the bin` : `${actor.name} moved ${live.length} contacts to the bin`,
    url: crmUrl('contacts'),
    about: live.map((c) => c.ownerId),
  });
  return live.length;
}

export async function deleteContact(id: string, actor: Actor) {
  await loadLive(id);
  await deleteContacts([id], actor);
}

export async function listBin(q: string | undefined, page = 1, limit = 25) {
  const where: Prisma.CrmContactWhereInput = {
    deletedAt: { not: null },
    ...(q?.trim() ? { AND: searchWhere(q) } : {}),
  };
  const [rows, total] = await Promise.all([
    prismaUnscoped.crmContact.findMany({
      where,
      orderBy: { deletedAt: 'desc' },
      skip: (page - 1) * limit,
      take: limit,
      select: { id: true, firstName: true, lastName: true, email: true, phone: true, companyName: true, deletedAt: true, deletedById: true },
    }),
    prismaUnscoped.crmContact.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,
      name: fullName(r),
      email: r.email,
      phone: r.phone,
      companyName: r.companyName,
      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 restoreContact(id: string, actor: Actor) {
  const c = await prismaUnscoped.crmContact.findFirst({ where: { id, deletedAt: { not: null } }, select: { id: true, firstName: true, lastName: true, ownerId: true } });
  if (!c) throw new NotFoundError('That contact is not in the bin');
  notify({ actor, text: `${actor.name} restored ${fullName(c)} from the bin`, url: crmUrl(`contacts/${id}`), about: [c.ownerId] });
  await prismaUnscoped.$transaction([
    prismaUnscoped.crmContact.update({ where: { id }, data: { deletedAt: null, deletedById: null, updatedById: actor.id } }),
    prismaUnscoped.crmActivity.create({ data: { contactId: id, type: CrmActivityType.RESTORED, actorId: actor.id, actorName: actor.name } }),
  ]);
  return getContact(id);
}

/** Remove for good whatever has sat in the bin longer than BIN_DAYS. */
export async function purgeBin(now = new Date()) {
  const cutoff = new Date(now.getTime() - BIN_DAYS * 86_400_000);
  const { count } = await prismaUnscoped.crmContact.deleteMany({ where: { deletedAt: { lt: cutoff } } });
  return count;
}

// ── Bulk ───────────────────────────────────────────────────────────────────

export type BulkAction =
  | { action: 'status'; value: CrmContactStatus }
  | { action: 'owner'; value: string | null }
  | { action: 'addToList' | 'removeFromList'; value: string }
  | { action: 'addTag' | 'removeTag'; value: string }
  | { action: 'delete' };

export async function bulk(ids: string[], op: BulkAction, actor: Actor): Promise<{ affected: number }> {
  if (op.action === 'delete') return { affected: await deleteContacts(ids, actor) };
  if (op.action === 'addToList' || op.action === 'removeFromList') {
    const affected = op.action === 'addToList' ? await addMembers(op.value, ids, actor) : await removeMembers(op.value, ids, actor);
    return { affected };
  }

  const live = await prismaUnscoped.crmContact.findMany({
    where: { id: { in: ids }, deletedAt: null },
    select: { id: true, status: true, ownerId: true, tags: true },
  });

  if (op.action === 'status') {
    const changed = live.filter((c) => c.status !== op.value);
    await prismaUnscoped.$transaction([
      prismaUnscoped.crmContact.updateMany({ where: { id: { in: changed.map((c) => c.id) } }, data: { status: op.value, updatedById: actor.id } }),
      prismaUnscoped.crmActivity.createMany({
        data: changed.map((c) => ({
          contactId: c.id,
          type: CrmActivityType.UPDATED,
          changes: [{ field: 'status', label: 'Status', from: c.status, to: op.value }],
          actorId: actor.id,
          actorName: actor.name,
        })),
      }),
    ]);
    if (op.value !== CrmContactStatus.NEW) await markTouched(changed.filter((c) => c.status === CrmContactStatus.NEW).map((c) => c.id));
    if (changed.length) notify({ actor, text: `${actor.name} set ${changed.length} contact${changed.length === 1 ? '' : 's'} to ${STATUS_LABEL[op.value]}`, url: crmUrl('contacts'), about: changed.map((c) => c.ownerId) });
    return { affected: changed.length };
  }

  if (op.action === 'owner') {
    if (op.value) await assertMember(op.value);
    const changed = live.filter((c) => c.ownerId !== op.value);
    const people = await prismaUnscoped.user.findMany({
      where: { id: { in: [op.value, ...changed.map((c) => c.ownerId)].filter((x): x is string => !!x) } },
      select: { id: true, name: true },
    });
    const nameOf = (uid: string | null) => people.find((p) => p.id === uid)?.name ?? null;
    await prismaUnscoped.$transaction([
      prismaUnscoped.crmContact.updateMany({ where: { id: { in: changed.map((c) => c.id) } }, data: { ownerId: op.value, updatedById: actor.id } }),
      prismaUnscoped.crmActivity.createMany({
        data: changed.map((c) => ({
          contactId: c.id,
          type: CrmActivityType.UPDATED,
          changes: [{ field: 'ownerId', label: 'Owner', from: nameOf(c.ownerId), to: nameOf(op.value) }],
          actorId: actor.id,
          actorName: actor.name,
        })),
      }),
    ]);
    if (changed.length) notify({ actor, text: `${actor.name} gave ${changed.length} contact${changed.length === 1 ? '' : 's'} to ${nameOf(op.value) ?? 'nobody'}`, url: crmUrl('contacts'), about: [op.value, ...changed.map((c) => c.ownerId)] });
    return { affected: changed.length };
  }

  // Tags: add or remove one, leaving every other tag as it is.
  const tag = cleanTags([op.value])[0];
  if (!tag) throw new BadRequestError('Enter a tag.');
  const lower = tag.toLowerCase();
  const changed = live
    .map((c) => {
      const has = c.tags.some((t) => t.toLowerCase() === lower);
      const next = op.action === 'addTag' ? (has ? null : [...c.tags, tag]) : has ? c.tags.filter((t) => t.toLowerCase() !== lower) : null;
      return next ? { id: c.id, from: c.tags, to: next } : null;
    })
    .filter((x): x is { id: string; from: string[]; to: string[] } => !!x);
  await prismaUnscoped.$transaction([
    ...changed.map((c) => prismaUnscoped.crmContact.update({ where: { id: c.id }, data: { tags: c.to, updatedById: actor.id } })),
    prismaUnscoped.crmActivity.createMany({
      data: changed.map((c) => ({
        contactId: c.id,
        type: CrmActivityType.UPDATED,
        changes: [{ field: 'tags', label: 'Tags', from: c.from, to: c.to }],
        actorId: actor.id,
        actorName: actor.name,
      })),
    }),
  ]);
  return { affected: changed.length };
}

/**
 * The Nurture list: leads to keep in touch with, not ready yet (a second
 * missed demo, three unanswered calls). Made the first time it is needed.
 */
export async function addToNurture(contactId: string, actor: { id: string; name: string }) {
  const name = 'Nurture';
  const list = await prismaUnscoped.crmList.upsert({
    where: { nameKey: name.toLowerCase() },
    update: {},
    create: { name, nameKey: name.toLowerCase(), description: 'Leads to keep in touch with: not ready yet.', color: 'amber', createdById: actor.id },
  });
  const added = await prismaUnscoped.crmListMember.createMany({ data: [{ listId: list.id, contactId, addedById: actor.id }], skipDuplicates: true });
  if (added.count) {
    await prismaUnscoped.crmActivity.create({ data: { contactId, type: CrmActivityType.LIST_ADDED, meta: { listId: list.id, list: list.name }, actorId: actor.id, actorName: actor.name } });
  }
  return list;
}

// ── Opt-out (L6) ───────────────────────────────────────────────────────────

/**
 * The unsubscribe link's token: the contact id and an HMAC of it, so it needs
 * no table and cannot be guessed for someone else.
 */
export function unsubscribeToken(contactId: string) {
  const sig = createHmac('sha256', `${env.JWT_REFRESH_SECRET}:crm-unsubscribe`).update(contactId).digest('base64url').slice(0, 32);
  return `${contactId}.${sig}`;
}

export const unsubscribeUrl = (contactId: string) => `${publicWebUrl}/unsubscribe?t=${encodeURIComponent(unsubscribeToken(contactId))}`;

export function contactIdFromToken(token: string): string | null {
  const [id, sig] = token.split('.');
  if (!id || !sig) return null;
  const want = unsubscribeToken(id).split('.')[1];
  const a = Buffer.from(sig);
  const b = Buffer.from(want);
  return a.length === b.length && timingSafeEqual(a, b) ? id : null;
}

/**
 * Stop (or resume) every automatic message to a contact. WhatsApp consent
 * goes with it; resuming does not bring WhatsApp consent back by itself.
 */
export async function setOptOut(contactId: string, optedOut: boolean, source: 'whatsapp' | 'email' | 'crm', actor: { id: string | null; name: string }, now = new Date()) {
  const c = await prismaUnscoped.crmContact.findUnique({ where: { id: contactId }, select: { id: true, optedOutAt: true } });
  if (!c) return false;
  if (optedOut === !!c.optedOutAt) return false;
  await prismaUnscoped.$transaction([
    prismaUnscoped.crmContact.update({
      where: { id: contactId },
      data: optedOut ? { optedOutAt: now, optOutSource: source, consentWhatsapp: false } : { optedOutAt: null, optOutSource: null, ...(source === 'whatsapp' ? { consentWhatsapp: true, consentAt: now, consentSource: 'Replied START on WhatsApp' } : {}) },
    }),
    prismaUnscoped.crmActivity.create({
      data: {
        contactId,
        type: CrmActivityType.UPDATED,
        changes: [{ field: 'optedOut', label: 'Messages', from: optedOut ? 'On' : 'Stopped', to: optedOut ? 'Stopped' : 'On' }],
        meta: { reason: optedOut ? 'opt-out' : 'opt-in', source },
        actorId: actor.id,
        actorName: actor.name,
        createdAt: now,
      },
    }),
  ]);
  return true;
}
