import 'dotenv/config';
import { PrismaPg } from '@prisma/adapter-pg';
import { PrismaClient } from '../src/generated/prisma/client';

// Repairs existing CDC G-PSF title rows created before the sidebar hierarchy.
// Only parentId changes; Admin-edited English/Khmer text is never overwritten.
const branches = [
  {
    group: 'group.wg',
    pages: ['dashboard', 'meeting_requests', 'meeting_calendar', 'meeting_summary', 'issue_matrix'],
  },
  {
    group: 'group.plenary',
    pages: ['plenary_dashboard', 'plenary_plenaries', 'plenary_rgc_decisions'],
  },
] as const;

async function main() {
  const connectionString = process.env.DATABASE_URL;
  if (!connectionString) throw new Error('DATABASE_URL is missing');
  const prisma = new PrismaClient({ adapter: new PrismaPg({ connectionString }) });
  const apply = process.argv.includes('--apply');
  try {
    const result = await prisma.$transaction(async tx => {
      const changes: Array<{ page: string; titleId: number; from: number | null; to: number }> = [];
      for (const branch of branches) {
        const parent = await tx.translation.findUnique({
          where: { module_page_translationKey: {
            module: 'cdcgpsf', page: 'sidebar', translationKey: branch.group,
          } },
          select: { id: true, parentId: true },
        });
        if (!parent || parent.parentId !== null)
          throw new Error(`Expected root sidebar group: ${branch.group}. No changes made.`);

        for (const page of branch.pages) {
          const title = await tx.translation.findUnique({
            where: { module_page_translationKey: {
              module: 'cdcgpsf', page, translationKey: 'title',
            } },
            select: { id: true, parentId: true },
          });
          if (!title || (title.parentId !== null && title.parentId !== parent.id))
            throw new Error(`Missing title or custom parent: ${page}. No changes made.`);
          if (title.parentId !== parent.id)
            changes.push({ page, titleId: title.id, from: title.parentId, to: parent.id });
        }
      }
      if (apply) {
        for (const change of changes) {
          await tx.translation.update({
            where: { id: change.titleId },
            data: { parentId: change.to },
          });
        }
      }
      return { applied: apply, changes };
    });
    console.log(JSON.stringify(result, null, 2));
  } finally {
    await prisma.$disconnect();
  }
}

main().catch(error => {
  console.error(error instanceof Error ? error.message : error);
  process.exitCode = 1;
});
