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

const databaseUrl = process.env.DATABASE_URL;

if (!databaseUrl) {
  throw new Error('Missing DATABASE_URL in environment for plan reset.');
}

const adapter = new PrismaPg({
  connectionString: databaseUrl,
});

const prisma = new PrismaClient({ adapter });

async function run() {
  const complexesUsingPlans = await prisma.complex.count({
    where: { planCode: { not: null } },
  });

  if (complexesUsingPlans > 0) {
    throw new Error(
      `No se puede resetear planes: hay ${complexesUsingPlans} complejos con plan asignado.`
    );
  }

  await prisma.$transaction(async (tx) => {
    await tx.plan.deleteMany({});

    for (const plan of planSeeds) {
      await tx.plan.create({
        data: {
          code: plan.code,
          name: plan.name,
          price: plan.price,
          rules: plan.rules,
        },
      });
    }
  });

  console.log('Planes reseteados: BASIC, ADVANCED, ENTERPRISE');
}

run()
  .then(async () => {
    await prisma.$disconnect();
  })
  .catch(async (error) => {
    console.error(error);
    await prisma.$disconnect();
    process.exit(1);
  });
