/**
 * Upsert contract-related indicator variables and point % indicators at provider_contract_target denominator.
 * Run after migration: npx tsx scripts/sync-contract-indicator-vars.ts
 */
import { prisma } from "../src/prisma.js";
import { SEED_VARIABLES, SEED_INDICATORS } from "../src/performanceSeedCatalog.js";

const CONTRACT_DENOM_CODES = new Set([
  "training_completion_rate",
  "trainee_dropout_rate",
  "eligible_enrolled_trainee_rate",
]);

async function main() {
  for (const v of SEED_VARIABLES) {
    await prisma.indicatorVariable.upsert({
      where: { code: v.code },
      create: {
        code: v.code,
        name: v.name,
        description: v.description,
        querySpec: v.querySpec,
      },
      update: {
        name: v.name,
        description: v.description,
        querySpec: v.querySpec,
      },
    });
  }

  const projects = await prisma.project.findMany({ select: { id: true } });
  for (const p of projects) {
    for (const seed of SEED_INDICATORS) {
      if (!CONTRACT_DENOM_CODES.has(seed.code)) continue;
      const existing = await prisma.projectIndicator.findFirst({
        where: { projectId: p.id, code: seed.code },
      });
      if (!existing) continue;
      await prisma.projectIndicator.update({
        where: { id: existing.id },
        data: {
          monitoringDenominatorVariable: seed.monDen,
          verificationDenominatorVariable: seed.verDen,
        },
      });
      console.log(`Updated project ${p.id} indicator ${seed.code}`);
    }
  }
  console.log("Done.");
}

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