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

const prisma = new PrismaClient();

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

  // 1. Clear existing data
  await prisma.review.deleteMany();
  await prisma.booking.deleteMany();
  await prisma.showtime.deleteMany();
  await prisma.seat.deleteMany();
  await prisma.hall.deleteMany();
  await prisma.movie.deleteMany();
  await prisma.user.deleteMany();
  console.log('🗑️  Cleared existing data');

  // 2. Create sample users
  const hashedPassword = await bcrypt.hash('password123', 10);
  const users = await prisma.user.createMany({
    data: [
      {
        name: 'John Doe',
        email: 'john@example.com',
        phone: '+1234567890',
        password: hashedPassword
      },
      {
        name: 'Jane Smith',
        email: 'jane@example.com',
        phone: '+1234567891',
        password: hashedPassword
      },
      {
        name: 'Admin User',
        email: 'admin@cinema.com',
        phone: '+1234567892',
        password: hashedPassword
      }
    ]
  });
  console.log('👥 Created sample users');

  // 3. Create sample movies with real poster URLs
  const movies = await prisma.movie.createMany({
    data: [
      {
        title: 'Dune: Part Two',
        genre: 'Sci-Fi, Adventure',
        durationMin: 166,
        posterUrl: 'https://image.tmdb.org/t/p/w500/8b8R8l88Qje9dn9OE8PY05Nxl1X.jpg',
        trailerUrl: 'https://www.youtube.com/watch?v=Way9Dexny3w',
        synopsis: 'Paul Atreides unites with Chani and the Fremen while seeking revenge against the conspirators who destroyed his family.',
        ratingAvg: 8.8
      },
      {
        title: 'Oppenheimer',
        genre: 'Biography, Drama, History',
        durationMin: 180,
        posterUrl: 'https://image.tmdb.org/t/p/w500/8Gxv8gSFCU0XGDykEGv7zR1n2ua.jpg',
        trailerUrl: 'https://www.youtube.com/watch?v=uYPbbksJxIg',
        synopsis: 'The story of American scientist J. Robert Oppenheimer and his role in the development of the atomic bomb.',
        ratingAvg: 8.5
      },
      {
        title: 'The Batman',
        genre: 'Action, Crime, Drama',
        durationMin: 176,
        posterUrl: 'https://image.tmdb.org/t/p/w500/74xTEgt7R36Fpooo50r9T25onhq.jpg',
        trailerUrl: 'https://www.youtube.com/watch?v=mqqft2x_Aa4',
        synopsis: 'When a sadistic serial killer begins murdering key political figures in Gotham, Batman is forced to investigate the city\'s hidden corruption.',
        ratingAvg: 7.9
      },
      {
        title: 'Avatar: The Way of Water',
        genre: 'Sci-Fi, Adventure, Action',
        durationMin: 192,
        posterUrl: 'https://image.tmdb.org/t/p/w500/t6HIqrRAclMCA60NsSmeqe9RmNV.jpg',
        trailerUrl: 'https://www.youtube.com/watch?v=d9MyW72ELq0',
        synopsis: 'Jake Sully and Ney\'tiri have formed a family and are doing everything to stay together. However, they must leave their home and explore the regions of Pandora.',
        ratingAvg: 7.7
      },
      {
        title: 'Spider-Man: Across the Spider-Verse',
        genre: 'Animation, Action, Adventure',
        durationMin: 140,
        posterUrl: 'https://image.tmdb.org/t/p/w500/8Vt6mWEReuy4Of61Lnj5Xj704m8.jpg',
        trailerUrl: 'https://www.youtube.com/watch?v=cqGjhVJWtEg',
        synopsis: 'Miles Morales catapults across the Multiverse, where he encounters a team of Spider-People charged with protecting its very existence.',
        ratingAvg: 8.7
      },
      {
        title: 'Inception',
        genre: 'Action, Sci-Fi, Thriller',
        durationMin: 148,
        posterUrl: 'https://image.tmdb.org/t/p/w500/9gk7adHYeDvHkCSEqAvQNLV5Uge.jpg',
        trailerUrl: 'https://www.youtube.com/watch?v=YoHD9XEInc0',
        synopsis: 'A thief who steals corporate secrets through dream-sharing technology is given the inverse task of planting an idea into the mind of a C.E.O.',
        ratingAvg: 8.8
      },
      {
        title: 'The Dark Knight',
        genre: 'Action, Crime, Drama',
        durationMin: 152,
        posterUrl: 'https://image.tmdb.org/t/p/w500/qJ2tW6WMUDux911r6m7haRef0WH.jpg',
        trailerUrl: 'https://www.youtube.com/watch?v=EXeTwQWrcwY',
        synopsis: 'When the menace known as the Joker wreaks havoc on Gotham, Batman must accept one of the greatest tests of his ability to fight injustice.',
        ratingAvg: 9.0
      },
      {
        title: 'Interstellar',
        genre: 'Adventure, Drama, Sci-Fi',
        durationMin: 169,
        posterUrl: 'https://image.tmdb.org/t/p/w500/gEU2QniE6E77NI6lCU6MxlNBvIx.jpg',
        trailerUrl: 'https://www.youtube.com/watch?v=zSWdZVtXT7E',
        synopsis: 'A team of explorers travel through a wormhole in space in an attempt to ensure humanity\'s survival.',
        ratingAvg: 8.7
      },
      {
        title: 'Guardians of the Galaxy Vol. 3',
        genre: 'Action, Adventure, Sci-Fi',
        durationMin: 150,
        posterUrl: 'https://image.tmdb.org/t/p/w500/r2J02Z2OpNTctfOSN1Ydgii51I3.jpg',
        trailerUrl: 'https://www.youtube.com/watch?v=u3V5KDHRQvk',
        synopsis: 'Still reeling from the loss of Gamora, Peter Quill rallies his team to defend the universe and one of their own.',
        ratingAvg: 8.0
      },
      {
        title: 'John Wick: Chapter 4',
        genre: 'Action, Thriller, Crime',
        durationMin: 169,
        posterUrl: 'https://image.tmdb.org/t/p/w500/vZloFAK7NmvMGKE7VkF5UHaz0I.jpg',
        trailerUrl: 'https://www.youtube.com/watch?v=qEVUtrk8_B4',
        synopsis: 'John Wick discovers a path to defeating The High Table. But before he can earn his freedom, Wick must face off against a new enemy.',
        ratingAvg: 8.2
      },
      {
        title: 'Top Gun: Maverick',
        genre: 'Action, Drama',
        durationMin: 131,
        posterUrl: 'https://image.tmdb.org/t/p/w500/62HCnUTziyWcpDaBO2i1DX17ljH.jpg',
        trailerUrl: 'https://www.youtube.com/watch?v=giXco2jaZ_4',
        synopsis: 'After thirty years, Maverick is still pushing the envelope as a top naval aviator, training a new generation for a specialized mission.',
        ratingAvg: 8.3
      },
      {
        title: 'The Super Mario Bros. Movie',
        genre: 'Animation, Adventure, Family',
        durationMin: 92,
        posterUrl: 'https://image.tmdb.org/t/p/w500/qNBAXBIQlnOThrVvA6mA2B5ggV6.jpg',
        trailerUrl: 'https://www.youtube.com/watch?v=TnGl01FkMMo',
        synopsis: 'A Brooklyn plumber named Mario travels through the Mushroom Kingdom with a princess named Peach and an anthropomorphic mushroom.',
        ratingAvg: 7.3
      }
    ]
  });
  console.log('🎬 Created 12 sample movies with real posters');

  // 4. Create cinema halls
  const halls = await prisma.hall.createMany({
    data: [
      { name: 'IMAX Hall', capacity: 200 },
      { name: 'Premium Hall', capacity: 100 },
      { name: 'Standard Hall A', capacity: 150 },
      { name: 'Standard Hall B', capacity: 150 },
      { name: 'VIP Hall', capacity: 50 }
    ]
  });
  console.log('🏛️  Created cinema halls');

  // 5. Get all movies and halls
  const allMovies = await prisma.movie.findMany();
  const allHalls = await prisma.hall.findMany();

  // 6. Create seats for all halls
  let totalSeats = 0;
  for (const hall of allHalls) {
    const seats = [];
    for (let i = 1; i <= hall.capacity; i++) {
      const row = String.fromCharCode(65 + Math.floor((i - 1) / 10)); // A, B, C, etc.
      const seatNumber = ((i - 1) % 10) + 1;
      seats.push({
        hallId: hall.id,
        label: `${row}${seatNumber}`
      });
    }
    await prisma.seat.createMany({ data: seats });
    totalSeats += seats.length;
  }
  console.log(`🪑 Created ${totalSeats} seats`);

  // 7. Create showtimes for next 7 days
  const showtimes = [];
  const basePrices = {
    'IMAX Hall': 18.0,
    'Premium Hall': 15.0,
    'Standard Hall A': 12.0,
    'Standard Hall B': 12.0,
    'VIP Hall': 25.0
  };

  for (let day = 0; day < 7; day++) {
    const date = new Date();
    date.setDate(date.getDate() + day);
    date.setHours(0, 0, 0, 0);

    for (const movie of allMovies) {
      // Each movie gets 3-4 showtimes per day across different halls
      const hallsForMovie = allHalls.slice(0, Math.floor(Math.random() * 2) + 2);
      
      for (const hall of hallsForMovie) {
        const times = ['10:00', '14:00', '18:00', '21:30'];
        const selectedTime = times[Math.floor(Math.random() * times.length)];
        const [hours, minutes] = selectedTime.split(':');
        
        const showDate = new Date(date);
        showDate.setHours(parseInt(hours), parseInt(minutes), 0, 0);

        showtimes.push({
          movieId: movie.id,
          hallId: hall.id,
          showDate,
          basePrice: basePrices[hall.name as keyof typeof basePrices]
        });
      }
    }
  }

  await prisma.showtime.createMany({ data: showtimes });
  console.log(`🎭 Created ${showtimes.length} showtimes`);

  // 8. Create sample reviews
  const allUsers = await prisma.user.findMany();
  const reviews = [];
  const reviewComments = [
    'Amazing movie! Highly recommended!',
    'Great cinematography and storyline.',
    'A masterpiece of modern cinema.',
    'Loved every minute of it!',
    'The best movie I\'ve seen this year.',
    'Incredible performance by the cast.',
    'A must-watch for all movie lovers.',
    'Stunning visuals and great sound.',
    'Epic movie experience!',
    'Worth every penny!'
  ];

  for (const movie of allMovies) {
    const numReviews = Math.floor(Math.random() * 5) + 3; // 3-7 reviews per movie
    for (let i = 0; i < numReviews; i++) {
      reviews.push({
        movieId: movie.id,
        userId: allUsers[Math.floor(Math.random() * allUsers.length)].id,
        rating: Math.floor(Math.random() * 3) + 3, // 3-5 stars
        comment: reviewComments[Math.floor(Math.random() * reviewComments.length)]
      });
    }
  }

  await prisma.review.createMany({ data: reviews });
  console.log(`⭐ Created ${reviews.length} sample reviews`);

  console.log('\n✅ Database seeding completed successfully!');
  console.log('📊 Summary:');
  console.log(`   - ${allUsers.length} users`);
  console.log(`   - ${allMovies.length} movies`);
  console.log(`   - ${allHalls.length} halls`);
  console.log(`   - ${totalSeats} seats`);
  console.log(`   - ${showtimes.length} showtimes`);
  console.log(`   - ${reviews.length} reviews`);
  console.log('\n🎉 You can now login with:');
  console.log('   Email: john@example.com');
  console.log('   Password: password123');
}

seed()
  .catch((e) => {
    console.error('❌ Seeding failed:', e);
    process.exit(1);
  })
  .finally(async () => {
    await prisma.$disconnect();
  });
