// Follow-up to importAsimWeeklyTasks.ts: turns the Excel columns into custom fields on
// every "General Weekly Tasks" board so they show up as Table view columns, and fills
// them per card (matched by the "Ref: XXX" line the import wrote into each description).
// Excel columns already covered by built-in columns are skipped: Görev -> Title,
// Durum -> Status, Son tarih -> Due date. Run with DRY_RUN=1 first.
import "dotenv/config";
import fs from "fs";
import { CustomFieldType, Prisma } from "@prisma/client";
import { prisma } from "../src/lib/prisma";

const DRY_RUN = process.env.DRY_RUN === "1";
const HUB_NAME = "General Weekly Tasks";

type Option = { label: string; color: string };
const FIELDS: { name: string; type: CustomFieldType; options?: Option[] }[] = [
  { name: "Ref", type: "TEXT" },
  { name: "Category", type: "TEXT" },
  { name: "This week", type: "CHECKBOX" },
  {
    name: "Priority",
    type: "DROPDOWN",
    options: [
      { label: "High", color: "#EF4444" },
      { label: "Medium", color: "#F59E0B" },
      { label: "Low", color: "#22C55E" },
    ],
  },
  { name: "Suggested next step", type: "TEXT" },
  { name: "Owner", type: "PERSON" },
  { name: "Waiting on", type: "TEXT" },
  {
    name: "Agenda section",
    type: "DROPDOWN",
    options: [
      { label: "Carried over", color: "#94A3B8" },
      { label: "New items", color: "#60A5FA" },
      { label: "Flagged emails", color: "#F87171" },
      { label: "Flagged emails (Jun–Aug)", color: "#FB923C" },
    ],
  },
  // TEXT, not NUMBER: the board/table views auto-sum every NUMBER field per list.
  { name: "Agenda no.", type: "TEXT" },
  { name: "Source", type: "TEXT" },
  {
    name: "Agenda mark",
    type: "DROPDOWN",
    options: [
      { label: "Circled", color: "#60A5FA" },
      { label: "Green (done)", color: "#22C55E" },
      { label: "Unmarked", color: "#9CA3AF" },
      { label: "Email flag", color: "#F87171" },
    ],
  },
  { name: "Notes", type: "TEXT" },
];

async function main() {
  const tasks: { ref: string; fields: Record<string, unknown> }[] = JSON.parse(fs.readFileSync(process.argv[2], "utf8"));
  const fieldsByRef = new Map(tasks.map((t) => [t.ref, t.fields]));

  const hub = await prisma.workspace.findFirstOrThrow({ where: { name: HUB_NAME } });
  const boards = await prisma.board.findMany({
    where: { workspaceId: hub.id },
    include: { customFields: true, lists: { select: { id: true } } },
    orderBy: { name: "asc" },
  });
  const summary: string[] = [];

  await prisma.$transaction(
    async (tx) => {
      for (const board of boards) {
        if (board.customFields.some((f) => FIELDS.some((d) => d.name === f.name))) {
          throw new Error(`${board.name} already has weekly-task custom fields — refusing to add them twice`);
        }
        const basePosition = Math.max(0, ...board.customFields.map((f) => f.position));
        const fieldId: Record<string, string> = {};
        for (const [i, def] of FIELDS.entries()) {
          const field = await tx.customField.create({
            data: {
              boardId: board.id,
              name: def.name,
              type: def.type,
              position: basePosition + (i + 1) * 1000,
              ...(def.options ? { options: def.options } : {}),
            },
          });
          fieldId[def.name] = field.id;
        }

        const cards = await tx.card.findMany({ where: { boardId: board.id }, select: { id: true, description: true } });
        const values: Prisma.CustomFieldValueCreateManyInput[] = [];
        for (const card of cards) {
          const ref = card.description?.match(/^Ref: (\S+)/)?.[1];
          const fields = ref ? fieldsByRef.get(ref) : undefined;
          if (!fields) throw new Error(`${board.name}: card ${card.id} has no matching Ref`);
          for (const def of FIELDS) {
            const value = fields[def.name];
            // Empty cells stay empty; an unticked checkbox is left unset rather than false.
            if (value === null || value === undefined || value === "" || value === false) continue;
            values.push({ cardId: card.id, customFieldId: fieldId[def.name], value: (def.type === "TEXT" ? String(value) : value) as Prisma.InputJsonValue });
          }
        }
        await tx.customFieldValue.createMany({ data: values });
        summary.push(`${board.name.padEnd(28)} ${String(cards.length).padStart(3)} cards  ${String(values.length).padStart(4)} values`);
      }

      if (DRY_RUN) throw Object.assign(new Error("DRY_RUN rollback"), { code: "DRY_RUN" });
    },
    { timeout: 300_000, maxWait: 30_000 }
  ).catch((err) => {
    if (DRY_RUN && err?.code === "DRY_RUN") return;
    throw err;
  });

  console.log(summary.join("\n"));
  console.log(DRY_RUN ? "\nDRY RUN — rolled back, nothing written." : "\nCustom fields committed.");
}

main()
  .catch((err) => {
    console.error(err);
    process.exitCode = 1;
  })
  .finally(() => prisma.$disconnect());
