import 'dotenv/config'
import { exec, queryOne, queryMany } from './pool';
import { logger } from '../lib/logger';
import { v4 as uuidv4 } from 'uuid';
import dotenv from 'dotenv';
dotenv.config();

async function seed() {
  logger.info('Seeding database...');

  const in2Days = new Date(Date.now() + 2 * 24 * 60 * 60 * 1000);
  const in5Days = new Date(Date.now() + 5 * 24 * 60 * 60 * 1000);
  const in7Days = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000);
  const in8Weeks = new Date(Date.now() + 56 * 24 * 60 * 60 * 1000);

  // Create season
  const existingSeason = await queryOne('SELECT id FROM seasons WHERE is_active = 1 LIMIT 1');
  let seasonId: string;

  if (!existingSeason) {
    seasonId = uuidv4();
    await exec(
      `INSERT INTO seasons (id, name, start_date, end_date, is_active) VALUES (?, ?, NOW(), ?, 1)`,
      [seasonId, 'Season 1: Prairie Pioneer', in8Weeks]
    );
    logger.info('Created season');
  } else {
    seasonId = (existingSeason as any).id;
    logger.info('Season already exists');
  }

  // Create starter shows
  const existingShows = await queryMany('SELECT id FROM shows LIMIT 1');
  if (!existingShows.length) {
    const shows = [
      { name: 'Weekly Rookie Roundup',           tier: 'rookie', fee: 10,  closes: in2Days },
      { name: 'Pro Breeders Classic',             tier: 'pro',    fee: 50,  closes: in5Days },
      { name: 'Elite Championship Invitational',  tier: 'elite',  fee: 200, closes: in7Days },
    ];

    for (const show of shows) {
      await exec(
        `INSERT INTO shows (id, name, tier, entry_fee, entry_closes_at, status, season_id)
         VALUES (?, ?, ?, ?, ?, 'open', ?)`,
        [uuidv4(), show.name, show.tier, show.fee, show.closes, seasonId]
      );
    }
    logger.info('Created starter shows');
  }

  logger.info('Seed complete.');
}

seed()
  .then(() => process.exit(0))
  .catch((err) => { logger.error('Seed failed', err); process.exit(1); });
