import fs from "fs";
import path from "path";
import type { CustomField, Prisma } from "@prisma/client";
import { HttpError } from "../middleware/errorHandler";
import { runCardMovedAutomations } from "./automations";
import { canEditCustomField } from "./customFieldAccess";
import { coerceCustomFieldValue } from "./customFields";
import { notifyUser } from "./notifications";
import { POSITION_GAP } from "./position";
import { prisma } from "./prisma";
import { emitToBoard } from "./socketBus";
import { uploadRoot } from "./upload";

// Shared core of the board "Import" feature. Both sources — an Excel sheet and the
// AI (image/voice) extraction — produce RawTasks that reference things by NAME
// (list "To do", member "joy@…", label "Urgent", column "Priority"). resolveTask()
// turns those into a Draft that references everything by id, which the frontend
// shows for review/editing and then sends back to commitDrafts().

export type RawTask = {
  cardId?: string | null;
  title?: string;
  description?: string | null;
  list?: string;
  status?: string;
  startDate?: unknown;
  dueDate?: unknown;
  members?: string[];
  labels?: string[];
  /** Custom column values keyed by column name. */
  fields?: Record<string, unknown>;
  /** Excel only: the columns present in the sheet. For an update, a column that
   * isn't in the sheet keeps the card's current value; undefined = all present. */
  present?: Set<string>;
};

export type DraftAttachment = { url: string; filename: string | null; mimeType: string | null; sizeBytes: number | null };

export type Draft = {
  key: string;
  source: string;
  cardId: string | null;
  title: string;
  description: string;
  listId: string;
  statusOptionId: string | null;
  startDate: string | null;
  dueDate: string | null;
  memberIds: string[];
  labelIds: string[];
  customFields: Record<string, unknown>;
  attachments: DraftAttachment[];
  warnings: string[];
};

export const MAX_IMPORT_ROWS = 1000;

export function normalizeName(value: string): string {
  return value
    .normalize("NFKD")
    .replace(/[̀-ͯ]/g, "")
    .toLocaleLowerCase("tr")
    .replace(/ı/g, "i")
    .replace(/\s+/g, " ")
    .trim();
}

export const COLUMN = {
  cardId: "card id",
  title: "title",
  description: "description",
  list: "list",
  status: "status",
  members: "members",
  labels: "labels",
  startDate: "start date",
  dueDate: "due date",
} as const;

// ---------- Board context ----------

export async function loadImportContext(boardId: string) {
  const board = await prisma.board.findUnique({
    where: { id: boardId },
    include: {
      lists: { where: { isArchived: false }, orderBy: { position: "asc" } },
      statusOptions: { orderBy: { position: "asc" } },
      labels: { orderBy: { name: "asc" } },
      customFields: { orderBy: { position: "asc" } },
      members: { include: { user: true } },
      workspaceLinks: { select: { workspaceId: true } },
    },
  });
  if (!board) throw new HttpError(404, "Board not found");
  if (board.lists.length === 0) throw new HttpError(400, "This board has no lists yet. Add a list before importing.");

  // Same "who can be assigned" rule as the board GET's effectiveMembers: explicit
  // board members plus workspace admins (home + linked) on non-Private/VIP boards.
  const assignable = new Map(board.members.map((m) => [m.userId, m.user]));
  if (board.visibility !== "PRIVATE" && board.visibility !== "VIP") {
    const admins = await prisma.workspaceMember.findMany({
      where: { workspaceId: { in: [board.workspaceId, ...board.workspaceLinks.map((l) => l.workspaceId)] }, role: "ADMIN" },
      include: { user: true },
    });
    for (const a of admins) if (!assignable.has(a.userId)) assignable.set(a.userId, a.user);
  }
  const members = [...assignable.values()].sort((a, b) => a.name.localeCompare(b.name));

  return {
    board,
    lists: board.lists,
    statuses: board.statusOptions,
    labels: board.labels,
    // FILE columns hold uploaded files and can't be filled from a sheet or the AI.
    fields: board.customFields.filter((f) => f.type !== "FILE"),
    members,
  };
}

export type ImportContext = Awaited<ReturnType<typeof loadImportContext>>;

/** Text block appended to the AI system prompt so it only uses names that exist. */
export function describeBoardForAi(ctx: ImportContext): string {
  const now = new Date();
  const today = new Intl.DateTimeFormat("en-CA", { timeZone: "Europe/London" }).format(now);
  const weekday = new Intl.DateTimeFormat("en-GB", { timeZone: "Europe/London", weekday: "long" }).format(now);
  const q = (s: string) => `"${s}"`;
  const fieldLines = ctx.fields.map((f) => {
    const options = (f.options as { label: string }[] | null)?.map((o) => o.label) ?? [];
    const hint: Record<string, string> = {
      TEXT: "text",
      LINK: "URL",
      NUMBER: "number",
      RATING: "number 1-5",
      CHECKBOX: 'checkbox: "yes" or "no"',
      DATE: "date YYYY-MM-DD",
      PERSON: "person: a member email",
      PHONE: "phone number",
      DROPDOWN: `one of: ${options.map(q).join(", ")}`,
      STATUS: `one of: ${options.map(q).join(", ")}`,
    };
    return `- ${q(f.name)} (${hint[f.type] ?? "text"})`;
  });
  return [
    `Today: ${weekday} ${today} (Europe/London).`,
    `Board: ${q(ctx.board.name)}`,
    `Lists (the first one is the default): ${ctx.lists.map((l) => q(l.name)).join(", ")}`,
    ctx.statuses.length ? `Statuses: ${ctx.statuses.map((s) => q(s.label)).join(", ")}` : "",
    ctx.labels.length ? `Labels: ${ctx.labels.map((l) => q(l.name)).join(", ")}` : "Labels: none",
    `Members (email - name):\n${ctx.members.slice(0, 200).map((m) => `- ${m.email} - ${m.name}`).join("\n")}`,
    fieldLines.length ? `Custom columns:\n${fieldLines.join("\n")}` : "",
  ]
    .filter(Boolean)
    .join("\n");
}

/** Vocabulary hint for speech-to-text: the names and terms people are likely to say. */
export function describeBoardForTranscription(ctx: ImportContext): string {
  const names = ctx.members.slice(0, 60).map((m) => m.name);
  return [
    `Voice note with tasks for the board "${ctx.board.name}".`,
    names.length ? `People: ${names.join(", ")}.` : "",
    ctx.labels.length ? `Labels: ${ctx.labels.map((l) => l.name).join(", ")}.` : "",
    `Lists: ${ctx.lists.map((l) => l.name).join(", ")}.`,
  ]
    .filter(Boolean)
    .join(" ");
}

// ---------- Value parsing ----------

const TRUE_WORDS = new Set(["true", "yes", "y", "1", "x", "✓", "✔", "evet", "checked", "done", "on"]);
const FALSE_WORDS = new Set(["false", "no", "n", "0", "hayir", "unchecked", "off", ""]);

function toDateString(d: Date): string | null {
  if (Number.isNaN(d.getTime())) return null;
  return d.toISOString().slice(0, 10);
}

/** Accepts Excel dates (Date objects or serial numbers), ISO strings and
 * day-first DD.MM.YYYY / DD/MM/YYYY. Returns YYYY-MM-DD, null for empty, or
 * undefined when the value can't be read as a date. */
export function parseDateValue(value: unknown): string | null | undefined {
  if (value === null || value === undefined || value === "") return null;
  if (value instanceof Date) return toDateString(value) ?? undefined;
  if (typeof value === "number") {
    return toDateString(new Date(Math.round((value - 25569) * 86_400_000))) ?? undefined;
  }
  const s = String(value).trim();
  if (!s) return null;
  const iso = s.match(/^(\d{4})-(\d{1,2})-(\d{1,2})/);
  if (iso) return toDateString(new Date(Date.UTC(+iso[1], +iso[2] - 1, +iso[3]))) ?? undefined;
  const dayFirst = s.match(/^(\d{1,2})[./-](\d{1,2})[./-](\d{2,4})$/);
  if (dayFirst) {
    const year = dayFirst[3].length === 2 ? 2000 + +dayFirst[3] : +dayFirst[3];
    return toDateString(new Date(Date.UTC(year, +dayFirst[2] - 1, +dayFirst[1]))) ?? undefined;
  }
  const parsed = Date.parse(s);
  return Number.isNaN(parsed) ? undefined : toDateString(new Date(parsed)) ?? undefined;
}

export function splitList(value: unknown): string[] {
  if (value === null || value === undefined) return [];
  if (Array.isArray(value)) return value.map(String).map((s) => s.trim()).filter(Boolean);
  return String(value)
    .split(/[,;\n]/)
    .map((s) => s.trim())
    .filter(Boolean);
}

/** "3.5", "3,5", "1,250.75" and "1.250,75" all read as intended: when both
 * separators appear the last one is the decimal point; a lone comma followed by
 * exactly three digits ("1,500") is a thousands separator, otherwise a decimal. */
export function parseLocaleNumber(input: string): number {
  let s = input.replace(/[\s£$€₺%]/g, "");
  const lastComma = s.lastIndexOf(",");
  const lastDot = s.lastIndexOf(".");
  if (lastComma !== -1 && lastDot !== -1) {
    s = lastComma > lastDot ? s.replace(/\./g, "").replace(",", ".") : s.replace(/,/g, "");
  } else if (lastComma !== -1) {
    s = /^-?\d{1,3}(,\d{3})+$/.test(s) ? s.replace(/,/g, "") : s.replace(",", ".");
  }
  return s === "" ? NaN : Number(s);
}

function findMember(ctx: ImportContext, token: string) {
  const n = normalizeName(token);
  return ctx.members.find(
    (m) => normalizeName(m.email) === n || normalizeName(m.username) === n || normalizeName(m.name) === n
  );
}

/** Converts a sheet/AI value for a custom column into its stored shape.
 * Returns { value } (null = empty) or { error }. */
function parseFieldValue(ctx: ImportContext, field: CustomField, raw: unknown): { value: unknown } | { error: string } {
  if (raw === null || raw === undefined || (typeof raw === "string" && raw.trim() === "")) return { value: null };
  const text = typeof raw === "string" ? raw.trim() : raw;
  switch (field.type) {
    case "NUMBER":
    case "RATING": {
      const n = typeof text === "number" ? text : parseLocaleNumber(String(text));
      return Number.isNaN(n) ? { error: `"${field.name}" expects a number, got "${text}"` } : { value: n };
    }
    case "CHECKBOX": {
      if (typeof text === "boolean") return { value: text || null };
      const n = normalizeName(String(text));
      if (TRUE_WORDS.has(n)) return { value: true };
      if (FALSE_WORDS.has(n)) return { value: null };
      return { error: `"${field.name}" expects yes/no, got "${text}"` };
    }
    case "DATE": {
      const d = parseDateValue(text);
      return d === undefined ? { error: `"${field.name}" expects a date, got "${text}"` } : { value: d };
    }
    case "DROPDOWN":
    case "STATUS": {
      const options = (field.options as { label: string }[] | null) ?? [];
      const match = options.find((o) => normalizeName(o.label) === normalizeName(String(text)));
      return match ? { value: match.label } : { error: `"${text}" isn't an option of "${field.name}"` };
    }
    case "PERSON": {
      const member = findMember(ctx, String(text));
      return member ? { value: member.id } : { error: `"${text}" for "${field.name}" isn't a member of this board` };
    }
    case "PHONE":
      return { value: { number: String(text), countryCode: null } };
    default:
      return { value: String(text) };
  }
}

/** Turns a stored custom field value back into what a sheet cell shows. */
export function fieldValueToCell(ctx: ImportContext, field: CustomField, value: unknown): string | number | boolean | Date | null {
  if (value === null || value === undefined) return null;
  switch (field.type) {
    case "CHECKBOX":
      return value === true ? "Yes" : null;
    case "NUMBER":
    case "RATING":
      return typeof value === "number" ? value : Number(value);
    case "DATE": {
      const d = parseDateValue(value);
      return d ? new Date(`${d}T00:00:00Z`) : null;
    }
    case "PERSON":
      return ctx.members.find((m) => m.id === value)?.email ?? null;
    case "PHONE":
      return (value as { number?: string })?.number ?? null;
    default:
      return String(value);
  }
}

// ---------- Resolve ----------

export type ExistingCard = Prisma.CardGetPayload<{
  include: { members: true; labels: true; customFieldValues: true };
}>;

export function resolveTask(
  ctx: ImportContext,
  raw: RawTask,
  meta: { key: string; source: string; existing?: ExistingCard | null }
): Draft {
  const warnings: string[] = [];
  const existing = meta.existing ?? null;
  const has = (column: string) => !existing || !raw.present || raw.present.has(column);

  const title = has(COLUMN.title) && raw.title?.trim() ? raw.title.trim() : existing?.title ?? raw.title?.trim() ?? "";
  if (!title) warnings.push("Title is empty");

  let listId = existing?.listId ?? ctx.lists[0].id;
  if (has(COLUMN.list) && raw.list?.trim()) {
    const list = ctx.lists.find((l) => normalizeName(l.name) === normalizeName(raw.list!));
    if (list) listId = list.id;
    else warnings.push(`List "${raw.list}" not found, using "${ctx.lists.find((l) => l.id === listId)?.name}"`);
  }

  let statusOptionId = existing?.statusOptionId ?? null;
  if (has(COLUMN.status)) {
    if (raw.status?.trim()) {
      const status = ctx.statuses.find((s) => normalizeName(s.label) === normalizeName(raw.status!));
      if (status) statusOptionId = status.id;
      else warnings.push(`Status "${raw.status}" not found`);
    } else if (existing && raw.present) {
      statusOptionId = null;
    }
  }

  const dateFrom = (column: string, value: unknown, current: Date | null | undefined, label: string) => {
    const fallback = current ? current.toISOString().slice(0, 10) : null;
    if (!has(column)) return fallback;
    const parsed = parseDateValue(value);
    if (parsed === undefined) {
      warnings.push(`${label} "${value}" isn't a valid date`);
      return fallback;
    }
    return parsed;
  };
  const startDate = dateFrom(COLUMN.startDate, raw.startDate, existing?.startDate, "Start date");
  const dueDate = dateFrom(COLUMN.dueDate, raw.dueDate, existing?.dueDate, "Due date");

  let memberIds = existing?.members.map((m) => m.userId) ?? [];
  if (has(COLUMN.members)) {
    memberIds = [];
    for (const token of raw.members ?? []) {
      const member = findMember(ctx, token);
      if (member) {
        if (!memberIds.includes(member.id)) memberIds.push(member.id);
      } else {
        warnings.push(`Member "${token}" isn't on this board`);
      }
    }
  }

  let labelIds = existing?.labels.map((l) => l.labelId) ?? [];
  if (has(COLUMN.labels)) {
    labelIds = [];
    for (const token of raw.labels ?? []) {
      const label = ctx.labels.find((l) => normalizeName(l.name) === normalizeName(token));
      if (label) {
        if (!labelIds.includes(label.id)) labelIds.push(label.id);
      } else {
        warnings.push(`Label "${token}" doesn't exist on this board`);
      }
    }
  }

  const customFields: Record<string, unknown> = {};
  for (const cfv of existing?.customFieldValues ?? []) customFields[cfv.customFieldId] = cfv.value;
  if (!existing) {
    // Same defaults a card created by hand gets, shown in the preview so they can be changed.
    for (const field of ctx.fields) {
      if (field.defaultValue === null) continue;
      try {
        const value = coerceCustomFieldValue(field.type, field.defaultValue, field.options as never);
        if (value !== null) customFields[field.id] = value;
      } catch {
        // stale default, ignore
      }
    }
  }
  const rawFields = new Map(Object.entries(raw.fields ?? {}).map(([name, value]) => [normalizeName(name), value]));
  for (const field of ctx.fields) {
    const n = normalizeName(field.name);
    if (!rawFields.has(n)) continue;
    const result = parseFieldValue(ctx, field, rawFields.get(n));
    if ("error" in result) {
      warnings.push(result.error);
      continue;
    }
    if (result.value === null) delete customFields[field.id];
    else customFields[field.id] = result.value;
  }
  const knownFields = new Set(ctx.fields.map((f) => normalizeName(f.name)));
  for (const name of Object.keys(raw.fields ?? {})) {
    if (!knownFields.has(normalizeName(name))) warnings.push(`Column "${name}" doesn't exist on this board, ignored`);
  }

  return {
    key: meta.key,
    source: meta.source,
    cardId: existing?.id ?? null,
    title: title.slice(0, 200),
    description: has(COLUMN.description) ? String(raw.description ?? "").trim() : existing?.description ?? "",
    listId,
    statusOptionId,
    startDate,
    dueDate,
    memberIds,
    labelIds,
    customFields,
    attachments: [],
    warnings,
  };
}

export async function loadExistingCards(boardId: string, cardIds: string[]) {
  if (cardIds.length === 0) return new Map<string, ExistingCard>();
  const cards = await prisma.card.findMany({
    where: { boardId, id: { in: cardIds } },
    include: { members: true, labels: true, customFieldValues: true },
  });
  return new Map(cards.map((c) => [c.id, c]));
}

// ---------- Commit ----------

export type DraftInput = Omit<Draft, "key" | "source" | "warnings">;

const ATTACHMENT_URL = /^\/uploads\/attachments\/[\w.-]+$/;

function toDateTime(date: string | null): Date | null {
  return date ? new Date(`${date}T09:00:00.000Z`) : null;
}

export async function commitDrafts(
  userId: string,
  boardId: string,
  drafts: DraftInput[],
  source: "import" | "assistant" = "import"
) {
  if (drafts.length === 0) throw new HttpError(400, "Nothing to import");
  if (drafts.length > MAX_IMPORT_ROWS) throw new HttpError(400, `You can import at most ${MAX_IMPORT_ROWS} tasks at once`);

  const ctx = await loadImportContext(boardId);
  const listIds = new Set(ctx.lists.map((l) => l.id));
  const statusIds = new Set(ctx.statuses.map((s) => s.id));
  const labelIds = new Set(ctx.labels.map((l) => l.id));
  const memberIds = new Set(ctx.members.map((m) => m.id));
  const fieldById = new Map(ctx.fields.map((f) => [f.id, f]));
  const editableFieldIds = new Set<string>();
  for (const field of ctx.fields) {
    if (await canEditCustomField(userId, boardId, field)) editableFieldIds.add(field.id);
  }

  const existingCards = await loadExistingCards(
    boardId,
    drafts.map((d) => d.cardId).filter((id): id is string => !!id)
  );

  const lastPositions = new Map<string, number>();
  for (const listId of listIds) {
    const last = await prisma.card.findFirst({
      where: { listId, isArchived: false, parentCardId: null },
      orderBy: { position: "desc" },
      select: { position: true },
    });
    lastPositions.set(listId, last?.position ?? 0);
  }
  const nextPosition = (listId: string) => {
    const p = (lastPositions.get(listId) ?? 0) + POSITION_GAP;
    lastPositions.set(listId, p);
    return p;
  };

  const skipped: string[] = [];
  const newAssignments = new Map<string, string[]>(); // userId -> cardIds
  const moved: { cardId: string; listId: string }[] = [];
  let created = 0;
  let updated = 0;

  const clean = (d: DraftInput, index: number) => {
    const title = d.title.trim().slice(0, 200);
    if (!title) {
      skipped.push(`Task ${index + 1}: title is empty`);
      return null;
    }
    const values: { fieldId: string; value: unknown }[] = [];
    for (const [fieldId, raw] of Object.entries(d.customFields ?? {})) {
      const field = fieldById.get(fieldId);
      if (!field) continue;
      try {
        const value = coerceCustomFieldValue(field.type, raw, field.options as never);
        values.push({ fieldId, value });
      } catch {
        skipped.push(`"${title}": invalid value for "${field.name}" ignored`);
      }
    }
    const attachments = (d.attachments ?? []).filter((a) => {
      const ok = ATTACHMENT_URL.test(a.url) && fs.existsSync(path.join(uploadRoot, "attachments", path.basename(a.url)));
      if (!ok) skipped.push(`"${title}": attachment "${a.filename ?? a.url}" not found, skipped`);
      return ok;
    });
    return {
      title,
      description: d.description?.trim() ? d.description.trim() : null,
      listId: listIds.has(d.listId) ? d.listId : ctx.lists[0].id,
      statusOptionId: d.statusOptionId && statusIds.has(d.statusOptionId) ? d.statusOptionId : null,
      startDate: toDateTime(d.startDate),
      dueDate: toDateTime(d.dueDate),
      memberIds: [...new Set(d.memberIds ?? [])].filter((id) => memberIds.has(id)),
      labelIds: [...new Set(d.labelIds ?? [])].filter((id) => labelIds.has(id)),
      values,
      attachments,
    };
  };

  await prisma.$transaction(
    async (tx) => {
      for (const [index, draft] of drafts.entries()) {
        const d = clean(draft, index);
        if (!d) continue;
        const existing = draft.cardId ? existingCards.get(draft.cardId) : undefined;
        if (draft.cardId && !existing) skipped.push(`"${d.title}": card to update no longer exists here, created as new`);

        if (!existing) {
          const members = d.memberIds.length > 0 ? d.memberIds : [userId];
          const card = await tx.card.create({
            data: {
              boardId,
              listId: d.listId,
              title: d.title,
              description: d.description,
              position: nextPosition(d.listId),
              statusOptionId: d.statusOptionId,
              startDate: d.startDate,
              dueDate: d.dueDate,
              members: { create: members.map((id) => ({ userId: id })) },
              labels: { create: d.labelIds.map((id) => ({ labelId: id })) },
              customFieldValues: {
                create: d.values
                  .filter((v) => v.value !== null && editableFieldIds.has(v.fieldId))
                  .map((v) => ({ customFieldId: v.fieldId, value: v.value as Prisma.InputJsonValue })),
              },
              attachments: {
                create: d.attachments.map((a) => ({
                  uploaderId: userId,
                  type: "file",
                  url: a.url,
                  filename: a.filename,
                  mimeType: a.mimeType,
                  sizeBytes: a.sizeBytes,
                })),
              },
            },
          });
          await tx.activityLog.create({
            data: { boardId, cardId: card.id, actorId: userId, action: "card.created", metadata: { title: d.title, source } },
          });
          for (const id of members) if (id !== userId) newAssignments.set(id, [...(newAssignments.get(id) ?? []), card.id]);
          created += 1;
          continue;
        }

        const listChanged = d.listId !== existing.listId;
        await tx.card.update({
          where: { id: existing.id },
          data: {
            title: d.title,
            description: d.description,
            statusOptionId: d.statusOptionId,
            startDate: d.startDate,
            dueDate: d.dueDate,
            ...(d.dueDate?.getTime() !== existing.dueDate?.getTime() ? { dueDateNotifiedAt: null } : {}),
            ...(listChanged ? { listId: d.listId, position: nextPosition(d.listId) } : {}),
          },
        });

        const currentMembers = new Set(existing.members.map((m) => m.userId));
        await tx.cardMember.deleteMany({ where: { cardId: existing.id, userId: { notIn: d.memberIds } } });
        const addedMembers = d.memberIds.filter((id) => !currentMembers.has(id));
        if (addedMembers.length) {
          await tx.cardMember.createMany({ data: addedMembers.map((id) => ({ cardId: existing.id, userId: id })), skipDuplicates: true });
        }
        for (const id of addedMembers) if (id !== userId) newAssignments.set(id, [...(newAssignments.get(id) ?? []), existing.id]);

        await tx.cardLabel.deleteMany({ where: { cardId: existing.id, labelId: { notIn: d.labelIds } } });
        if (d.labelIds.length) {
          await tx.cardLabel.createMany({ data: d.labelIds.map((id) => ({ cardId: existing.id, labelId: id })), skipDuplicates: true });
        }

        const currentValues = new Map(existing.customFieldValues.map((v) => [v.customFieldId, v.value]));
        const draftFieldIds = new Set(d.values.map((v) => v.fieldId));
        const changes = [
          ...d.values.map((v) => ({ fieldId: v.fieldId, value: v.value })),
          // A column dropped from the draft entirely means "cleared".
          ...[...currentValues.keys()].filter((id) => fieldById.has(id) && !draftFieldIds.has(id)).map((id) => ({ fieldId: id, value: null })),
        ];
        for (const change of changes) {
          if (JSON.stringify(currentValues.get(change.fieldId) ?? null) === JSON.stringify(change.value)) continue;
          if (!editableFieldIds.has(change.fieldId)) {
            skipped.push(`"${d.title}": you can't edit "${fieldById.get(change.fieldId)?.name}", left unchanged`);
            continue;
          }
          if (change.value === null) {
            await tx.customFieldValue.deleteMany({ where: { cardId: existing.id, customFieldId: change.fieldId } });
          } else {
            await tx.customFieldValue.upsert({
              where: { cardId_customFieldId: { cardId: existing.id, customFieldId: change.fieldId } },
              update: { value: change.value as Prisma.InputJsonValue },
              create: { cardId: existing.id, customFieldId: change.fieldId, value: change.value as Prisma.InputJsonValue },
            });
          }
        }

        if (d.attachments.length) {
          await tx.attachment.createMany({
            data: d.attachments.map((a) => ({
              cardId: existing.id,
              uploaderId: userId,
              type: "file",
              url: a.url,
              filename: a.filename,
              mimeType: a.mimeType,
              sizeBytes: a.sizeBytes,
            })),
          });
        }

        await tx.activityLog.create({
          data: { boardId, cardId: existing.id, actorId: userId, action: source === "assistant" ? "card.assistant_updated" : "card.import_updated", metadata: { title: d.title } },
        });
        if (listChanged) {
          await tx.activityLog.create({
            data: {
              boardId,
              cardId: existing.id,
              actorId: userId,
              action: "card.moved",
              metadata: { fromListId: existing.listId, toListId: d.listId },
            },
          });
          moved.push({ cardId: existing.id, listId: d.listId });
        }
        updated += 1;
      }
    },
    { timeout: 180_000, maxWait: 20_000 }
  );

  for (const m of moved) await runCardMovedAutomations(m.cardId, boardId, m.listId, userId);

  // One notification per person rather than one per card, so a big sheet doesn't
  // flood anyone's inbox.
  for (const [recipientId, cardIds] of newAssignments) {
    await notifyUser({
      recipientId,
      actorId: userId,
      type: "ASSIGNMENT",
      message:
        cardIds.length === 1
          ? `You were added to a card on "${ctx.board.name}"`
          : `You were added to ${cardIds.length} cards on "${ctx.board.name}"`,
      cardId: cardIds[0],
      boardId,
    });
  }

  emitToBoard(boardId, "board:changed", {});
  return { created, updated, skipped };
}
