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

// Explicit legacy-data repair, separate from the create-only translation seed.
// Only Ministry's three unparented Plenary page titles are changed.
async function main() {
  if (!process.env.DATABASE_URL) throw new Error('DATABASE_URL is missing');
  const prisma = new PrismaClient({
    adapter: new PrismaPg({ connectionString: process.env.DATABASE_URL }),
  });
  try {
    const result = await prisma.$transaction(async (tx) => {
      const parent = await tx.translation.findUnique({
        where: {
          module_page_translationKey: {
            module: 'ministry',
            page: 'sidebar',
            translationKey: 'group.plenary',
          },
        },
      });
      if (!parent || parent.parentId !== null)
        throw new Error(
          'Expected a root Ministry Plenary group. No changes made.',
        );
      const pages = [
        'plenary_dashboard',
        'plenary_plenaries',
        'plenary_rgc_decisions',
      ];
      const before = await tx.translation.findMany({
        where: {
          module: 'ministry',
          page: { in: pages },
          translationKey: 'title',
        },
        select: { id: true, page: true, parentId: true },
      });
      if (
        before.length !== pages.length ||
        before.some(
          (row) => row.parentId !== null && row.parentId !== parent.id,
        )
      ) {
        throw new Error(
          'Missing page or custom parent detected. No changes made.',
        );
      }
      const updated = await tx.translation.updateMany({
        where: {
          id: { in: before.map((row) => row.id) },
          module: 'ministry',
          parentId: null,
        },
        data: { parentId: parent.id },
      });
      const after = await tx.translation.findMany({
        where: { id: { in: before.map((row) => row.id) } },
        select: { id: true, page: true, parentId: true },
      });
      return { updated: updated.count, parentId: parent.id, before, after };
    });
    console.log(JSON.stringify(result, null, 2));
  } finally {
    await prisma.$disconnect();
  }
}
main().catch((error) => {
  console.error(
    error instanceof Error
      ? error.message
      : 'Translation hierarchy repair failed.',
  );
  process.exitCode = 1;
});
