import 'dotenv/config';
import fs from 'fs';
import path from 'path';
import { PrismaClient } from '@prisma/client';
import { getProjectRoot } from '../src/lib/projectPaths';

const prisma = new PrismaClient();

/** hr-data legacy 상시업무 — 허브 대분류 셸로 대체, 시드·DB에서 제거 */
const LEGACY_ROUTINE_TITLES = [
  'H/W, S/W',
  '시설관리',
  '배움터',
  '인재채용',
  '학습 지원',
  '채용 운영',
];

async function deleteLegacyRoutineTasks() {
  for (const title of LEGACY_ROUTINE_TITLES) {
    const task = await prisma.task.findFirst({
      where: { title, taskType: { in: ['기반업무', '상시업무'] } },
    });
    if (!task) {
      console.log(`  skip (not found): ${title}`);
      continue;
    }
    await prisma.task.delete({ where: { id: task.id } });
    console.log(`  🗑 deleted: ${title}`);
  }

  const remaining = await prisma.task.count({
    where: { taskType: { in: ['기반업무', '상시업무'] } },
  });
  if (remaining > 0) {
    const extras = await prisma.task.findMany({
      where: { taskType: { in: ['기반업무', '상시업무'] } },
      select: { title: true },
    });
    for (const t of extras) {
      await prisma.task.deleteMany({ where: { title: t.title, taskType: { in: ['기반업무', '상시업무'] } } });
      console.log(`  🗑 deleted (extra routine): ${t.title}`);
    }
  }
}

function patchHrData() {
  const seedPath = path.join(getProjectRoot(), 'data', 'seed', 'hr-data.json');
  const data = JSON.parse(fs.readFileSync(seedPath, 'utf-8')) as {
    PROJECTS: { name: string; priority?: string; [key: string]: unknown }[];
  };

  const before = data.PROJECTS.length;
  data.PROJECTS = data.PROJECTS.filter((p) => p.priority !== '상시');

  fs.writeFileSync(seedPath, JSON.stringify(data, null, 2), 'utf-8');
  console.log(`  ✓ hr-data.json: removed ${before - data.PROJECTS.length} legacy 상시 entries (${data.PROJECTS.length} projects left)`);
}

async function main() {
  console.log('🧹 Delete all legacy routine tasks from DB ...');
  await deleteLegacyRoutineTasks();

  console.log('📝 Remove priority:상시 from hr-data.json ...');
  patchHrData();

  console.log('Done. 상시업무는 허브에서 대분류 클릭 시 새 셸로 생성됩니다.');
}

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