/**
 * Backfill cohort.location_id for existing data:
 * - Multi-site training: one cohort per delivery site (if missing)
 * - Single-site: set null cohort locations from the training's only delivery site
 *
 * Usage: npx tsx scripts/backfill-cohort-locations.ts
 */
import "dotenv/config";
import { PrismaClient } from "@prisma/client";
import {
  ensureCohortsForDeliverySites,
  ensureMainCohortAndBatchForTraining,
  parseDeliveryLocationIds,
  SINGLE_SITE_COHORT_CODE,
} from "../src/services/trainingScopeGuards.js";

async function main() {
  const prisma = new PrismaClient();
  try {
    const trainings = await prisma.training.findMany({
      select: {
        id: true,
        projectId: true,
        trainingProviderId: true,
        deliveryLocationIds: true,
        locationId: true,
        startDate: true,
        endDate: true,
        timelineAnchorDate: true,
        sessionWeekdays: true,
      },
    });

    let updatedCohorts = 0;
    let createdCohorts = 0;

    for (const tr of trainings) {
      const siteIds = parseDeliveryLocationIds(tr.deliveryLocationIds);
      const effective =
        siteIds.length > 0 ? siteIds : tr.locationId ? [tr.locationId] : [];

      if (effective.length === 0) continue;

      if (effective.length === 1) {
        const locId = effective[0]!;
        const cohorts = await prisma.trainingCohort.findMany({
          where: { trainingId: tr.id, locationId: null },
          select: { id: true },
        });
        for (const c of cohorts) {
          await prisma.trainingCohort.update({
            where: { id: c.id },
            data: { locationId: locId },
          });
          updatedCohorts += 1;
        }
        const hasMain = await prisma.trainingCohort.findFirst({
          where: { trainingId: tr.id, code: SINGLE_SITE_COHORT_CODE },
          select: { id: true },
        });
        if (!hasMain) {
          await ensureMainCohortAndBatchForTraining(prisma, {
            projectId: tr.projectId,
            trainingProviderId: tr.trainingProviderId,
            trainingId: tr.id,
            locationId: locId,
            startDate: tr.startDate,
            endDate: tr.endDate,
            timelineAnchorDate: tr.timelineAnchorDate,
            sessionWeekdays: tr.sessionWeekdays,
          });
          createdCohorts += 1;
        }
      } else {
        const before = await prisma.trainingCohort.count({ where: { trainingId: tr.id } });
        await ensureCohortsForDeliverySites(prisma, {
          projectId: tr.projectId,
          trainingProviderId: tr.trainingProviderId,
          trainingId: tr.id,
          deliveryLocationIds: effective,
          startDate: tr.startDate,
          endDate: tr.endDate,
          timelineAnchorDate: tr.timelineAnchorDate,
          sessionWeekdays: tr.sessionWeekdays,
        });
        const after = await prisma.trainingCohort.count({ where: { trainingId: tr.id } });
        createdCohorts += Math.max(0, after - before);
        const legacyMain = await prisma.trainingCohort.findFirst({
          where: { trainingId: tr.id, code: SINGLE_SITE_COHORT_CODE, locationId: null },
          select: { id: true },
        });
        if (legacyMain && effective[0]) {
          await prisma.trainingCohort.update({
            where: { id: legacyMain.id },
            data: { locationId: effective[0] },
          });
          updatedCohorts += 1;
        }
      }
    }

    console.log(`Backfill complete. Cohorts updated: ${updatedCohorts}, cohorts created: ${createdCohorts}.`);
    console.log("Re-run trainee import scope is unchanged; location counts use cohort delivery sites.");
  } finally {
    await prisma.$disconnect();
  }
}

void main().catch((e) => {
  console.error(e);
  process.exit(1);
});
