/**
 * task.section 레거시 값 정규화 + 조직문화(EX) 재배치
 * npx tsx scripts/normalize-task-sections.ts
 */
import 'dotenv/config';
import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

const EX_TITLE = /회사생활|C\.E\.L|조직문화|복리후생|문화\s*진단|직원\s*소통/i;

const SECTION_MAP: Record<string, string> = {
  성장지원: '학습성장',
  HR: '인사관리',
  운영지원: '운영관리',
  전산관리: '운영관리',
};

async function main() {
  const tasks = await prisma.task.findMany({
    select: { id: true, title: true, section: true, category: true, taskType: true },
  });

  let renamed = 0;
  let exMoved = 0;

  for (const task of tasks) {
    const section = task.section?.trim() ?? '';
    let nextSection = SECTION_MAP[section] ?? section;

    if (nextSection !== '조직문화' && EX_TITLE.test(task.title.trim())) {
      nextSection = '조직문화';
      exMoved += 1;
    }

    const patch: { section?: string; category?: string | null } = {};
    if (nextSection && nextSection !== section) {
      patch.section = nextSection;
      renamed += 1;
    }
    if (nextSection === '조직문화' && task.category !== '조직문화') {
      patch.category = '조직문화';
    }

    if (Object.keys(patch).length > 0) {
      await prisma.task.update({ where: { id: task.id }, data: patch });
      console.log(`  section: ${section || '(empty)'} → ${nextSection} | ${task.title}`);
    }
  }

  const col = await prisma.columnConfig.findUnique({ where: { key: '운영관리' } });
  if (col && (col.title === '운영관리' || col.title === '운영관리 부문' || col.titleEn === 'Operations')) {
    await prisma.columnConfig.update({
      where: { key: '운영관리' },
      data: { title: '총무관리', titleEn: 'GA' },
    });
    console.log('  columnConfig 운영관리 → 총무관리');
  }

  const hrd = await prisma.columnConfig.findUnique({ where: { key: '학습성장' } });
  if (hrd && (hrd.title === '학습성장' || hrd.title === '성장지원' || hrd.titleEn === 'Learning & Growth')) {
    await prisma.columnConfig.update({
      where: { key: '학습성장' },
      data: { title: '인재육성', titleEn: 'HRD' },
    });
    console.log('  columnConfig 학습성장 → 인재육성');
  }

  console.log(`\n✅ normalize-task-sections complete (${renamed} renamed, ${exMoved} → 조직문화)`);
}

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