import fs from 'fs';
import path from 'path';
import mongoose from 'mongoose';
import dotenv from 'dotenv';
import { SportModel, LeagueModel, ParticipantModel, WidgetTypeModel, TemplateModel } from '../src/models';
import { SeedData } from '../src/types';

dotenv.config();

const SEED_FILE_PATH = path.join(__dirname, '..', 'sportpulse_widgets_seed.json');

async function seedDatabase(): Promise<void> {
  const mongoUri = process.env.MONGODB_URI || 'mongodb://localhost:27017/sportpulse';

  console.log('Connecting to MongoDB...');
  await mongoose.connect(mongoUri);
  console.log('Connected to MongoDB');

  console.log('Reading seed file...');
  const rawData = fs.readFileSync(SEED_FILE_PATH, 'utf-8');
  const seedData: SeedData = JSON.parse(rawData);

  console.log(`Seed data version: ${seedData.version}`);
  console.log(`Sports: ${seedData.sports.length}`);
  console.log(`Leagues: ${seedData.leagues.length}`);
  console.log(`Participants: ${seedData.participants.length}`);
  console.log(`Widget Types: ${seedData.widgetTypes.length}`);
  console.log(`Templates: ${seedData.templates.length}`);

  // Clear existing data
  console.log('\nClearing existing data...');
  await Promise.all([
    SportModel.deleteMany({}),
    LeagueModel.deleteMany({}),
    ParticipantModel.deleteMany({}),
    WidgetTypeModel.deleteMany({}),
    TemplateModel.deleteMany({}),
  ]);

  // Insert sports
  console.log('Inserting sports...');
  await SportModel.insertMany(seedData.sports);

  // Insert leagues (map iconUrl to leagueLogoUrl)
  console.log('Inserting leagues...');
  const leaguesWithLogoUrl = seedData.leagues.map(league => ({
    ...league,
    leagueLogoUrl: league.iconUrl,
  }));
  await LeagueModel.insertMany(leaguesWithLogoUrl);

  // Insert participants
  if (seedData.participants.length > 0) {
    console.log('Inserting participants...');
    await ParticipantModel.insertMany(seedData.participants);
  }

  // Insert widget types
  console.log('Inserting widget types...');
  await WidgetTypeModel.insertMany(seedData.widgetTypes);

  // Insert templates
  console.log('Inserting templates...');
  await TemplateModel.insertMany(seedData.templates);

  console.log('\nSeed completed successfully!');

  // Print summary
  const sportCount = await SportModel.countDocuments();
  const leagueCount = await LeagueModel.countDocuments();
  const participantCount = await ParticipantModel.countDocuments();
  const widgetTypeCount = await WidgetTypeModel.countDocuments();
  const templateCount = await TemplateModel.countDocuments();

  console.log('\nDatabase summary:');
  console.log(`  Sports: ${sportCount}`);
  console.log(`  Leagues: ${leagueCount}`);
  console.log(`  Participants: ${participantCount}`);
  console.log(`  Widget Types: ${widgetTypeCount}`);
  console.log(`  Templates: ${templateCount}`);

  await mongoose.disconnect();
  console.log('\nDisconnected from MongoDB');
}

seedDatabase().catch((error) => {
  console.error('Seed failed:', error);
  process.exit(1);
});
