/**
 * 전산관리·운영지원 → 운영관리 부문 통합 (1회 실행)
 * 사용: npm run db:migrate-sections
 */
import 'dotenv/config';
import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

const MERGE_INTO = '운영관리';
const FROM = ['전산관리', '운영지원'] as const;

async function mergeCardOrder(intoKey: string, fromKeys: readonly string[]) {
  const target = await prisma.columnConfig.findUnique({ where: { key: intoKey } });
  const orders: string[] = [];
  if (target?.cardOrder) {
    try {
      orders.push(...JSON.parse(target.cardOrder));
    } catch {
      /* ignore */
    }
  }
  for (const from of fromKeys) {
    const src = await prisma.columnConfig.findUnique({ where: { key: from } });
    if (!src?.cardOrder) continue;
    try {
      const ids = JSON.parse(src.cardOrder) as string[];
      for (const id of ids) {
        if (!orders.includes(id)) orders.push(id);
      }
    } catch {
      /* ignore */
    }
  }
  if (orders.length === 0 && !target) return;
  await prisma.columnConfig.upsert({
    where: { key: intoKey },
    update: { cardOrder: JSON.stringify(orders) },
    create: {
      key: intoKey,
      title: '운영관리',
      titleEn: 'GA',
      subtitle: '',
      cardOrder: JSON.stringify(orders),
    },
  });
}

async function main() {
  for (const from of FROM) {
    const { count } = await prisma.task.updateMany({
      where: { section: from },
      data: { section: MERGE_INTO },
    });
    if (count > 0) console.log(`  ✓ ${from} → ${MERGE_INTO}: ${count} tasks`);
  }
  await mergeCardOrder(MERGE_INTO, FROM);
  console.log('✅ Section migration done.');
}

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