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

const prisma = new PrismaClient()

async function main() {
  console.log('🌱 Seeding database...')

  // Criar usuários de exemplo
  const user1 = await prisma.user.create({
    data: {
      email: 'user1@example.com',
      username: 'user1',
      password: await bcrypt.hash('password123', 10),
      nickname: 'João',
    },
  })

  const user2 = await prisma.user.create({
    data: {
      email: 'user2@example.com',
      username: 'user2',
      password: await bcrypt.hash('password123', 10),
      nickname: 'Maria',
    },
  })

  console.log('✅ Users criados')

  // Criar torneio
  const tournament = await prisma.tournament.create({
    data: {
      name: 'Copa do Mundo 2026',
      sport: 'football',
      year: 2026,
      startDate: new Date('2026-06-01'),
      endDate: new Date('2026-07-31'),
      status: 'active',
    },
  })

  console.log('✅ Tournament criado')

  // Criar estágio de grupos
  const groupStage = await prisma.stage.create({
    data: {
      tournamentId: tournament.id,
      name: 'Group Stage',
      stageNumber: 1,
      startDate: new Date('2026-06-01'),
      endDate: new Date('2026-06-30'),
    },
  })

  console.log('✅ Group Stage criado')

  // Criar grupos (A-H)
  const groups = await Promise.all(
    ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'].map((groupName) =>
      prisma.group.create({
        data: {
          stageId: groupStage.id,
          name: groupName,
        },
      })
    )
  )

  console.log('✅ Grupos criados')

  // Criar times
  const teams = [
    { name: 'Brasil', code: 'BRA', flag: '🇧🇷' },
    { name: 'Argentina', code: 'ARG', flag: '🇦🇷' },
    { name: 'Alemanha', code: 'GER', flag: '🇩🇪' },
    { name: 'França', code: 'FRA', flag: '🇫🇷' },
    { name: 'Espanha', code: 'ESP', flag: '🇪🇸' },
    { name: 'Portugal', code: 'POR', flag: '🇵🇹' },
    { name: 'Inglaterra', code: 'ENG', flag: '🇬🇧' },
    { name: 'Itália', code: 'ITA', flag: '🇮🇹' },
    { name: 'Holanda', code: 'NED', flag: '🇳🇱' },
    { name: 'Bélgica', code: 'BEL', flag: '🇧🇪' },
    { name: 'Suíça', code: 'SUI', flag: '🇨🇭' },
    { name: 'México', code: 'MEX', flag: '🇲🇽' },
    { name: 'Uruguai', code: 'URU', flag: '🇺🇾' },
    { name: 'Colômbia', code: 'COL', flag: '🇨🇴' },
    { name: 'Japão', code: 'JPN', flag: '🇯🇵' },
    { name: 'Coreia do Sul', code: 'KOR', flag: '🇰🇷' },
  ]

  const createdTeams = await Promise.all(
    teams.map((team) =>
      prisma.team.create({
        data: team,
      })
    )
  )

  console.log('✅ Times criados')

  // Adicionar times aos grupos
  for (let i = 0; i < groups.length; i++) {
    for (let j = 0; j < 4; j++) {
      const teamIndex = (i * 4 + j) % createdTeams.length
      await prisma.groupTeam.create({
        data: {
          groupId: groups[i].id,
          teamId: createdTeams[teamIndex].id,
          position: j + 1,
        },
      })
    }
  }

  console.log('✅ Times adicionados aos grupos')

  // Criar matches de exemplo no grupo A
  const groupA = groups[0]
  const teamsBRA = await prisma.team.findUnique({ where: { code: 'BRA' } })
  const teamsARG = await prisma.team.findUnique({ where: { code: 'ARG' } })
  const teamsGER = await prisma.team.findUnique({ where: { code: 'GER' } })
  const teamsFRA = await prisma.team.findUnique({ where: { code: 'FRA' } })

  const matches = [
    {
      homeTeamId: teamsBRA!.id,
      awayTeamId: teamsARG!.id,
      kickoffTime: new Date('2026-06-05T14:00:00Z'),
    },
    {
      homeTeamId: teamsGER!.id,
      awayTeamId: teamsFRA!.id,
      kickoffTime: new Date('2026-06-05T18:00:00Z'),
    },
    {
      homeTeamId: teamsBRA!.id,
      awayTeamId: teamsGER!.id,
      kickoffTime: new Date('2026-06-10T14:00:00Z'),
    },
    {
      homeTeamId: teamsARG!.id,
      awayTeamId: teamsFRA!.id,
      kickoffTime: new Date('2026-06-10T18:00:00Z'),
    },
  ]

  for (let i = 0; i < matches.length; i++) {
    await prisma.match.create({
      data: {
        stageId: groupStage.id,
        groupId: groupA.id,
        matchNumber: i + 1,
        ...matches[i],
      },
    })
  }

  console.log('✅ Matches criados')

  // Criar participantes no torneio
  await prisma.tournamentParticipant.create({
    data: {
      tournamentId: tournament.id,
      userId: user1.id,
    },
  })

  await prisma.tournamentParticipant.create({
    data: {
      tournamentId: tournament.id,
      userId: user2.id,
    },
  })

  console.log('✅ Tournament participants criados')

  console.log('✨ Seed completed!')
}

main()
  .catch((e) => {
    console.error(e)
    process.exit(1)
  })
  .finally(async () => {
    await prisma.$disconnect()
  })
