/* ------------------------------------------------------------------
 * IncrelogEMS — seed the landing pricing slabs (idempotent).
 *
 *   npx tsx scripts/seed-pricing.ts
 *
 * Six slabs per card (0–3500 students); institutions above 3500 use the
 * "Contact For Custom Offer" flow on the landing page instead of a
 * seventh slab. Two price matrices by sector — central admins can still
 * tune every number from Central → Landing Pricing. Re-running never
 * duplicates; slabs that no longer exist in the matrix are deactivated
 * (kept only if a subscription still references them, then deleted).
 * ------------------------------------------------------------------ */
"use strict";

import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();

/** the six student-count slabs shown on every landing pricing card */
const RANGES: Array<{ min: number; max: number }> = [
  { min: 0, max: 300 },
  { min: 301, max: 500 },
  { min: 501, max: 1000 },
  { min: 1001, max: 1500 },
  { min: 1501, max: 2500 },
  { min: 2501, max: 3500 },
];

/** non-government institutions (school / college / university / coaching):
 *  yearly payment takes 25% off the 12-month total */
const NON_GOVT = { discount: 25, prices: [2700, 4500, 8000, 11000, 16000, 20000] };

/** government institutions (school / college / university) and madrasa:
 *  yearly payment takes 20% off the 12-month total */
const GOVT = { discount: 20, prices: [1500, 2500, 4000, 6500, 9500, 13000] };

const CATEGORIES: Array<{ code: string; discount: number; prices: number[] }> = [
  { code: "NON_GOVT_SCHOOL", ...NON_GOVT },
  { code: "NON_GOVT_COLLEGE_UNIV", ...NON_GOVT },
  { code: "COACHING", ...NON_GOVT },
  { code: "GOVT_SCHOOL", ...GOVT },
  { code: "GOVT_COLLEGE_UNIV", ...GOVT },
  { code: "MADRASHA", ...GOVT },
];

async function main() {
  for (const cat of CATEGORIES) {
    let order = 0;
    for (let i = 0; i < RANGES.length; i++) {
      const range = RANGES[i];
      const data = {
        category: cat.code,
        minStudents: range.min,
        maxStudents: range.max,
        monthlyPrice: cat.prices[i],
        yearlyDiscount: cat.discount,
        active: true,
        sortOrder: order++,
      };
      const existing = await prisma.pricingTier.findFirst({
        where: { category: data.category, minStudents: data.minStudents },
      });
      if (existing) {
        await prisma.pricingTier.update({ where: { id: existing.id }, data });
        console.log(`  ≈ ${data.category} ${data.minStudents}-${data.maxStudents} → ৳${data.monthlyPrice}/mo`);
      } else {
        await prisma.pricingTier.create({ data });
        console.log(`  ✓ ${data.category} ${data.minStudents}-${data.maxStudents} → ৳${data.monthlyPrice}/mo (yearly −${cat.discount}%)`);
      }
    }

    // retire slabs outside the matrix — keep (hidden) only when a
    // subscription still points at them, otherwise delete
    const keep = new Set(RANGES.map((r) => r.min));
    const stale = await prisma.pricingTier.findMany({
      where: { category: cat.code, minStudents: { notIn: [...keep] } },
    });
    for (const tier of stale) {
      const refs = await prisma.subscription.count({ where: { pricingTierId: tier.id } });
      if (refs > 0) {
        await prisma.pricingTier.update({ where: { id: tier.id }, data: { active: false } });
        console.log(`  − ${cat.code} ${tier.minStudents}+ kept hidden (${refs} subscription reference)`);
      } else {
        await prisma.pricingTier.delete({ where: { id: tier.id } });
        console.log(`  × ${cat.code} ${tier.minStudents}+ removed`);
      }
    }
  }
  const total = await prisma.pricingTier.count();
  console.log(`\nPricing tiers in DB: ${total}`);
}

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