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

const databaseUrl = process.env.DATABASE_URL;

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

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

const prisma = new PrismaClient({ adapter });

async function run() {
  for (const plan of planSeeds) {
    await prisma.plan.upsert({
      where: { code: plan.code },
      update: {
        name: plan.name,
        price: plan.price,
        rules: plan.rules,
        lastUpdatedAt: new Date(),
      },
      create: {
        code: plan.code,
        name: plan.name,
        price: plan.price,
        rules: plan.rules,
      },
    });
  }

  for (const sport of sportSeeds) {
    await prisma.sport.upsert({
      where: { slug: sport.slug },
      update: {
        name: sport.name,
        isActive: true,
      },
      create: {
        id: uuidv7(),
        name: sport.name,
        slug: sport.slug,
        isActive: true,
      },
    });
  }
}

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