// One-off import of Asım Bey's "Weekly Tasks / CEO Action List" (Weekly_Tasks_28Sep2026.xlsx,
// pre-translated to English into import.json). One board per category, all living in a
// new "General Weekly Tasks" workspace and linked into the matching category workspace.
// A task with several categories (e.g. "Finance / Legal") gets a card on each of those
// boards. Run with DRY_RUN=1 first: everything happens in one transaction that is then
// rolled back.
import "dotenv/config";
import fs from "fs";
import { Prisma } from "@prisma/client";
import { prisma } from "../src/lib/prisma";
import { uniqueWorkspaceSlug } from "../src/lib/slugs";

type Task = {
  ref: string;
  title: string;
  description: string;
  categories: string[];
  list: "To do" | "Needs Confirmation" | "Done";
  flag: boolean;
  thisWeek: boolean;
  extraLabels: string[];
  due: string | null;
  users: string[];
};

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

const ORG = {
  dmc: "cmrm47w4m0003i95sokkgmvvc",
  hospitality: "cmtabamph01fqhjdask8e3ky0",
  lim: "cmudzuqtt02nghjg1uflzu2aq",
  private: "cmtlapv8f008khjcj7n8lpjzd",
};

// Category -> the workspace its board is linked into: an existing workspace id, or
// an organization to create a same-named workspace in.
const CATEGORY_WORKSPACE: Record<string, { id: string } | { org: string }> = {
  Finance: { id: "cmudyhqlj02klhjg1q9yzbr6h" },
  IT: { id: "cmrm47w4r0005i95s67z2k8e5" },
  Marketing: { id: "cmrm47w6x000ji95sqx5w8c0a" },
  Sales: { id: "cmrm47w7s000xi95sjsm9npbm" },
  Legal: { org: ORG.dmc },
  Management: { org: ORG.dmc },
  BD: { org: ORG.dmc },
  HR: { org: ORG.dmc },
  Uninist: { org: ORG.dmc },
  LEA: { org: ORG.dmc },
  "New Brands": { org: ORG.dmc },
  LHS: { org: ORG.hospitality },
  LIM: { org: ORG.lim },
  Personal: { org: ORG.private },
};

const LISTS = ["To do", "In progress", "Needs Confirmation", "Done"] as const;
const STATUSES = [
  { label: "Not started", color: "#9CA3AF" },
  { label: "In progress", color: "#3B82F6" },
  { label: "Needs confirmation", color: "#F59E0B" },
  { label: "Done", color: "#22C55E" },
];
const LIST_STATUS: Record<string, string> = {
  "To do": "Not started",
  "In progress": "In progress",
  "Needs Confirmation": "Needs confirmation",
  Done: "Done",
};
const GRADIENTS = ["gradient-ocean", "gradient-sunset", "gradient-forest", "gradient-grape", "gradient-sky", "gradient-peach", "gradient-mint", "gradient-fire"];
const CATEGORY_COLORS = ["#60A5FA", "#34D399", "#A78BFA", "#F472B6", "#94A3B8", "#FB923C", "#2DD4BF", "#818CF8", "#A3E635", "#E879F9", "#38BDF8", "#FCD34D", "#C084FC", "#4ADE80"];
const FIXED_LABELS: Record<string, string> = { Flag: "#F87171", "This week": "#FBBF24", Turkey: "#F43F5E" };

async function main() {
  const tasks: Task[] = JSON.parse(fs.readFileSync(process.argv[2], "utf8"));
  const categories = [...new Set(tasks.flatMap((t) => t.categories))];
  for (const c of categories) if (!CATEGORY_WORKSPACE[c]) throw new Error(`No workspace mapping for category ${c}`);
  const categoryColor = Object.fromEntries(categories.map((c, i) => [c, CATEGORY_COLORS[i % CATEGORY_COLORS.length]]));

  const usernames = [...new Set(tasks.flatMap((t) => t.users))];
  const users = await prisma.user.findMany({ where: { username: { in: usernames } }, select: { id: true, username: true } });
  const userId = Object.fromEntries(users.map((u) => [u.username, u.id]));
  const missing = usernames.filter((u) => !userId[u]);
  if (missing.length) throw new Error(`Unknown usernames: ${missing.join(", ")}`);

  if (await prisma.workspace.findFirst({ where: { organizationId: ORG.dmc, name: HUB_NAME } })) {
    throw new Error(`"${HUB_NAME}" already exists — refusing to import twice`);
  }
  // Slugs are computed outside the transaction (the helper uses the global client).
  const newWorkspaceNames = [HUB_NAME, ...categories.filter((c) => "org" in CATEGORY_WORKSPACE[c])];
  const slugs: Record<string, string> = {};
  for (const name of newWorkspaceNames) slugs[name] = await uniqueWorkspaceSlug(name);

  const summary: string[] = [];

  await prisma.$transaction(
    async (tx) => {
      const addWorkspaceMember = async (workspaceId: string, uid: string, role: "ADMIN" | "MEMBER") => {
        const ws = await tx.workspace.findUniqueOrThrow({ where: { id: workspaceId }, select: { organizationId: true } });
        await tx.organizationMember.upsert({
          where: { organizationId_userId: { organizationId: ws.organizationId, userId: uid } },
          update: {},
          create: { organizationId: ws.organizationId, userId: uid, role: "MEMBER" },
        });
        const existing = await tx.workspaceMember.findUnique({ where: { workspaceId_userId: { workspaceId, userId: uid } } });
        if (!existing) await tx.workspaceMember.create({ data: { workspaceId, userId: uid, role } });
        else if (role === "ADMIN" && existing.role !== "ADMIN") await tx.workspaceMember.update({ where: { id: existing.id }, data: { role } });
      };

      const hub = await tx.workspace.create({
        data: {
          organizationId: ORG.dmc,
          name: HUB_NAME,
          slug: slugs[HUB_NAME],
          description: "Asım Bey's weekly task list (CEO action list), one board per category.",
        },
      });
      await addWorkspaceMember(hub.id, ASIM, "ADMIN");

      for (const [i, category] of categories.entries()) {
        const target = CATEGORY_WORKSPACE[category];
        const categoryWorkspaceId =
          "id" in target
            ? target.id
            : (await tx.workspace.create({ data: { organizationId: target.org, name: category, slug: slugs[category] } })).id;
        await addWorkspaceMember(categoryWorkspaceId, ASIM, "ADMIN");

        const boardTasks = tasks.filter((t) => t.categories.includes(category));
        const assignees = [...new Set(boardTasks.flatMap((t) => t.users.map((u) => userId[u])))].filter((id) => id !== ASIM);

        const otherCategories = [...new Set(boardTasks.flatMap((t) => t.categories))].filter((c) => c !== category);
        const labelNames = ["Flag", "This week", ...new Set(boardTasks.flatMap((t) => t.extraLabels)), ...otherCategories];

        const board = await tx.board.create({
          data: {
            workspaceId: hub.id,
            name: `${category} Weekly Tasks`,
            description: `${category} items from Asım Bey's weekly task list (28 Sep 2026).`,
            // Personal items are private to Asım (plus whoever is assigned) — VIP is the
            // only tier org owners don't automatically see.
            visibility: category === "Personal" ? "VIP" : "WORKSPACE",
            backgroundType: "GRADIENT",
            backgroundValue: GRADIENTS[i % GRADIENTS.length],
            members: {
              create: [{ userId: ASIM, role: "ADMIN" }, ...assignees.map((id) => ({ userId: id, role: "MEMBER" as const }))],
            },
            statusOptions: { create: STATUSES.map((s, j) => ({ ...s, position: (j + 1) * 1000 })) },
            lists: { create: LISTS.map((name, j) => ({ name, position: (j + 1) * 1000 })) },
            labels: {
              create: labelNames.map((name) => ({ name, color: FIXED_LABELS[name] ?? categoryColor[name] })),
            },
          },
          include: { lists: true, statusOptions: true, labels: true },
        });
        await tx.workspaceBoardLink.create({ data: { workspaceId: categoryWorkspaceId, boardId: board.id } });
        for (const id of assignees) await addWorkspaceMember(categoryWorkspaceId, id, "MEMBER");

        const listId = Object.fromEntries(board.lists.map((l) => [l.name, l.id]));
        const statusId = Object.fromEntries(board.statusOptions.map((s) => [s.label, s.id]));
        const labelId = Object.fromEntries(board.labels.map((l) => [l.name, l.id]));
        const positions: Record<string, number> = {};

        for (const t of boardTasks) {
          positions[t.list] = (positions[t.list] ?? 0) + 1000;
          const cardLabels = [
            ...(t.flag ? ["Flag"] : []),
            ...(t.thisWeek ? ["This week"] : []),
            ...t.extraLabels,
            ...t.categories.filter((c) => c !== category),
          ];
          const cardUsers = [...new Set([ASIM, ...t.users.map((u) => userId[u])])];
          await tx.card.create({
            data: {
              boardId: board.id,
              listId: listId[t.list],
              title: t.title,
              description: t.description,
              position: positions[t.list],
              isCompleted: t.list === "Done",
              statusOptionId: statusId[LIST_STATUS[t.list]],
              dueDate: t.due ? new Date(`${t.due}T09:00:00Z`) : null,
              members: { create: cardUsers.map((id) => ({ userId: id })) },
              labels: { create: cardLabels.map((name) => ({ labelId: labelId[name] })) },
            },
          });
        }
        summary.push(
          `${board.name.padEnd(28)} ${String(boardTasks.length).padStart(3)} cards  -> ws ${categoryWorkspaceId}  members: ${assignees.length + 1}`
        );
      }

      if (DRY_RUN) throw new Prisma.PrismaClientKnownRequestError("DRY_RUN rollback", { code: "DRY_RUN", clientVersion: "x" });
    },
    { 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." : "\nImport committed.");
}

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