import { PrismaClient } from '@prisma/client';
import bcrypt from 'bcryptjs';

const prisma = new PrismaClient();

async function main() {
  console.log('🌱 Starting database seed...');

  // 1. Seed Leagues
  console.log('📊 Seeding leagues...');
  const leagues = await Promise.all([
    prisma.league.upsert({
      where: { code: 'EPL' },
      update: {},
      create: {
        name: 'English Premier League',
        code: 'EPL',
        category: 'club',
        countryCode: 'ENG',
        displayOrder: 1,
        isActive: true,
      },
    }),
    prisma.league.upsert({
      where: { code: 'UCL' },
      update: {},
      create: {
        name: 'UEFA Champions League',
        code: 'UCL',
        category: 'club',
        displayOrder: 2,
        isActive: true,
      },
    }),
    prisma.league.upsert({
      where: { code: 'LIGA1' },
      update: {},
      create: {
        name: 'Liga Indonesia',
        code: 'LIGA1',
        category: 'club',
        countryCode: 'IDN',
        displayOrder: 3,
        isActive: true,
      },
    }),
    prisma.league.upsert({
      where: { code: 'WC' },
      update: {},
      create: {
        name: 'FIFA World Cup',
        code: 'WC',
        category: 'country',
        displayOrder: 4,
        isActive: true,
      },
    }),
    prisma.league.upsert({
      where: { code: 'LALIGA' },
      update: {},
      create: {
        name: 'La Liga',
        code: 'LALIGA',
        category: 'club',
        countryCode: 'ESP',
        displayOrder: 5,
        isActive: true,
      },
    }),
    prisma.league.upsert({
      where: { code: 'BUN' },
      update: {},
      create: {
        name: 'Bundesliga',
        code: 'BUN',
        category: 'club',
        countryCode: 'GER',
        displayOrder: 6,
        isActive: true,
      },
    }),
    prisma.league.upsert({
      where: { code: 'SERIEA' },
      update: {},
      create: {
        name: 'Serie A',
        code: 'SERIEA',
        category: 'club',
        countryCode: 'ITA',
        displayOrder: 7,
        isActive: true,
      },
    }),
  ]);
  console.log(`✅ Created ${leagues.length} leagues`);

  // 2. Seed Clubs (EPL)
  console.log('⚽ Seeding clubs...');
  const eplLeague = leagues.find(l => l.code === 'EPL');
  if (eplLeague) {
    const clubs = await Promise.all([
      prisma.club.upsert({
        where: { code: 'ARS' },
        update: {},
        create: {
          name: 'Arsenal',
          code: 'ARS',
          leagueId: eplLeague.id,
          isActive: true,
        },
      }),
      prisma.club.upsert({
        where: { code: 'CHE' },
        update: {},
        create: {
          name: 'Chelsea',
          code: 'CHE',
          leagueId: eplLeague.id,
          isActive: true,
        },
      }),
      prisma.club.upsert({
        where: { code: 'MUN' },
        update: {},
        create: {
          name: 'Manchester United',
          code: 'MUN',
          leagueId: eplLeague.id,
          isActive: true,
        },
      }),
      prisma.club.upsert({
        where: { code: 'MCI' },
        update: {},
        create: {
          name: 'Manchester City',
          code: 'MCI',
          leagueId: eplLeague.id,
          isActive: true,
        },
      }),
      prisma.club.upsert({
        where: { code: 'LIV' },
        update: {},
        create: {
          name: 'Liverpool',
          code: 'LIV',
          leagueId: eplLeague.id,
          isActive: true,
        },
      }),
      prisma.club.upsert({
        where: { code: 'TOT' },
        update: {},
        create: {
          name: 'Tottenham',
          code: 'TOT',
          leagueId: eplLeague.id,
          isActive: true,
        },
      }),
    ]);
    console.log(`✅ Created ${clubs.length} clubs`);
  }

  // 3. Seed Teams (National)
  console.log('🌍 Seeding national teams...');
  const teams = await Promise.all([
    prisma.team.upsert({
      where: { countryCode: 'ENG' },
      update: {},
      create: {
        name: 'England',
        countryCode: 'ENG',
        isActive: true,
      },
    }),
    prisma.team.upsert({
      where: { countryCode: 'BRA' },
      update: {},
      create: {
        name: 'Brazil',
        countryCode: 'BRA',
        isActive: true,
      },
    }),
    prisma.team.upsert({
      where: { countryCode: 'IDN' },
      update: {},
      create: {
        name: 'Indonesia',
        countryCode: 'IDN',
        isActive: true,
      },
    }),
    prisma.team.upsert({
      where: { countryCode: 'ARG' },
      update: {},
      create: {
        name: 'Argentina',
        countryCode: 'ARG',
        isActive: true,
      },
    }),
    prisma.team.upsert({
      where: { countryCode: 'FRA' },
      update: {},
      create: {
        name: 'France',
        countryCode: 'FRA',
        isActive: true,
      },
    }),
    prisma.team.upsert({
      where: { countryCode: 'GER' },
      update: {},
      create: {
        name: 'Germany',
        countryCode: 'GER',
        isActive: true,
      },
    }),
  ]);
  console.log(`✅ Created ${teams.length} national teams`);

  // 4. Seed Marketplace Items
  console.log('🛒 Seeding marketplace items...');
  const items = await Promise.all([
    prisma.marketplaceItem.create({
      data: {
        name: 'Premium 1-Month Pass',
        description: 'Unlock all premium features for 30 days',
        category: 'premium_pass',
        pricePoints: 5000,
        priceCoins: 2000,
        isActive: true,
        displayOrder: 1,
      },
    }),
    prisma.marketplaceItem.create({
      data: {
        name: 'Gold Avatar Frame',
        description: 'Exclusive gold frame for your avatar',
        category: 'cosmetic',
        priceCoins: 1000,
        stockQuantity: 100,
        isActive: true,
        displayOrder: 2,
      },
    }),
    prisma.marketplaceItem.create({
      data: {
        name: 'Username Color: Gold',
        description: 'Change your username color to gold',
        category: 'cosmetic',
        priceCoins: 500,
        isActive: true,
        displayOrder: 3,
      },
    }),
    prisma.marketplaceItem.create({
      data: {
        name: 'Prediction Boost (24h)',
        description: 'Get 2x points for all predictions for 24 hours',
        category: 'boost',
        priceCoins: 800,
        isActive: true,
        displayOrder: 4,
      },
    }),
    prisma.marketplaceItem.create({
      data: {
        name: 'Diamond Badge',
        description: 'Exclusive diamond badge for your profile',
        category: 'badge',
        priceCoins: 1500,
        stockQuantity: 50,
        isActive: true,
        displayOrder: 5,
      },
    }),
  ]);
  console.log(`✅ Created ${items.length} marketplace items`);

  // 5. Seed Admin User
  console.log('👤 Seeding admin user...');
  const adminPassword = process.env.ADMIN_DEFAULT_PASSWORD || 'Admin@2024!';
  const hashedPassword = await bcrypt.hash(adminPassword, 10);
  const admin = await prisma.adminUser.upsert({
    where: { email: 'admin@aiprediction.com' },
    update: { passwordHash: hashedPassword },
    create: {
      username: 'admin',
      email: 'admin@aiprediction.com',
      passwordHash: hashedPassword,
      role: 'super_admin',
      isActive: true,
    },
  });
  console.log(`✅ Created admin user: ${admin.email}`);

  console.log('');
  console.log('🎉 Database seeding completed successfully!');
  console.log('');
  console.log('📝 Summary:');
  console.log(`   - ${leagues.length} leagues`);
  console.log(`   - 6 clubs (EPL)`);
  console.log(`   - ${teams.length} national teams`);
  console.log(`   - 0 missions (managed via admin panel)`);
  console.log(`   - ${items.length} marketplace items`);
  console.log(`   - 1 admin user`);
  console.log('');
  console.log('🔐 Admin Credentials:');
  console.log('   Username: admin');
  console.log(`   Password: ${adminPassword}`);
  console.log('');
}

main()
  .catch((e) => {
    console.error('❌ Error seeding database:', e);
    process.exit(1);
  })
  .finally(async () => {
    await prisma.$disconnect();
  });
