import { PrismaClient, type Level } from '@prisma/client'
import bcrypt from 'bcryptjs'
import dotenv from 'dotenv'
import path from 'path'
import fs from 'fs'

// Load environment variables only if DATABASE_URL not provided by runtime
if (!process.env.DATABASE_URL) {
  // Try .env.local first, then .env
  const envPath = path.resolve(process.cwd(), '.env.local')
  if (fs.existsSync(envPath)) {
    dotenv.config({ path: envPath, override: true })
    console.log('📁 Using .env.local for database connection')
  } else {
    dotenv.config({ override: true })
    console.log('📁 Using .env for database connection')
  }
} else {
  console.log('📁 Using DATABASE_URL from environment')
}

const prisma = new PrismaClient({ log: ['warn', 'error'] })

const LEVELS: Level[] = ['A1', 'A2', 'B1', 'B2', 'C1', 'C2']

function levelForIndex(i: number): Level {
  return LEVELS[i % LEVELS.length]
}

export async function seedFakeStudentsAndBots() {
  const countStudents = 15
  const countBots = 15

  console.log(`🧪 Seeding fake data: ${countStudents} students, ${countBots} bots...`)

  // Ensure teacher exists to attach students (so they appear in teacher dashboards)
  const teacher = await prisma.user.findUnique({ where: { email: 'teacher@example.com' } })
  if (!teacher) {
    throw new Error('Teacher user not found (teacher@example.com). Run the main seed first: npm run prisma:seed')
  }

  // Also use teacher as creator for bots (createdBy is optional, but helps filtering/ownership)
  const createdBy = teacher.id

  // Create students
  console.log('👩‍🎓 Creating/updating fake students...')
  for (let i = 1; i <= countStudents; i++) {
    const n = String(i).padStart(2, '0')
    const email = `student+fake${n}@example.com`
    const name = `Fake Student ${n}`
    const passwordPlain = `TestStudent#${n}!`
    const passwordHash = await bcrypt.hash(passwordPlain, 12)

    const student = await prisma.user.upsert({
      where: { email },
      update: {
        name,
        password: passwordHash,
        role: 'STUDENT',
        emailVerified: true,
      },
      create: {
        email,
        name,
        password: passwordHash,
        role: 'STUDENT',
        emailVerified: true,
      },
      select: { id: true, email: true, name: true },
    })

    // Assign teacher to student (idempotent)
    await prisma.studentTeacherAssignment.upsert({
      where: {
        studentId_teacherId: {
          studentId: student.id,
          teacherId: teacher.id,
        },
      },
      update: {},
      create: {
        studentId: student.id,
        teacherId: teacher.id,
      },
    })

    console.log(`✅ Student: ${student.email} (password: ${passwordPlain})`)
  }

  // Create bots (inactive; agentId is unique-ish but not validated here)
  console.log('🤖 Creating/updating fake bots...')
  for (let i = 1; i <= countBots; i++) {
    const n = String(i).padStart(2, '0')
    const level = levelForIndex(i - 1)
    const name = `Test Bot ${n}`
    const agentId = `test-agent-fake-${n}`

    const existing = await prisma.bot.findFirst({ where: { name } })
    if (existing) {
      await prisma.bot.update({
        where: { id: existing.id },
        data: {
          topic: `Test Topic ${n}`,
          level,
          agentId,
          description: `Bot de prueba ${n} para verificar paginación y listados.`,
          feedback: `Feedback de prueba para el bot ${n}.`,
          isActive: false,
          createdBy,
          imageUrl: null,
          isTimerEnabled: false,
          maxUsageSeconds: null,
        },
      })
      console.log(`✅ Bot updated: ${name}`)
    } else {
      await prisma.bot.create({
        data: {
          name,
          topic: `Test Topic ${n}`,
          level,
          agentId,
          description: `Bot de prueba ${n} para verificar paginación y listados.`,
          feedback: `Feedback de prueba para el bot ${n}.`,
          isActive: false,
          createdBy,
          imageUrl: null,
          isTimerEnabled: false,
          maxUsageSeconds: null,
        },
      })
      console.log(`✅ Bot created: ${name}`)
    }
  }

  const createdStudents = await prisma.user.count({
    where: { email: { contains: 'student+fake', mode: 'insensitive' } },
  })
  const createdBots = await prisma.bot.count({
    where: { name: { startsWith: 'Test Bot ' } },
  })

  console.log('🎉 Fake seed completed!')
  console.log(`📊 Counts (approx): students(fake)=${createdStudents}, bots(test)=${createdBots}`)
}

async function main() {
  await seedFakeStudentsAndBots()
}

if (require.main === module) {
  main()
    .catch((e) => {
      console.error('❌ Error during fake seed:', e)
      process.exit(1)
    })
    .finally(async () => {
      await prisma.$disconnect()
    })
}

