// prisma/seed.ts
import { PrismaClient, UserRole, ContentStatus, ProficiencyLevel, ExerciseType } from '@prisma/client'
import { Pool } from 'pg'
import { PrismaPg } from '@prisma/adapter-pg'

const connectionString = process.env.DIRECT_URL

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

  // 1. Setup the Adapter (Crucial for Prisma 7 + Serverless)
  const pool = new Pool({ connectionString })
  const adapter = new PrismaPg(pool)
  const prisma = new PrismaClient({ adapter })

  try {
    // 2. Create a Teacher/Super Admin
    const teacher = await prisma.profile.upsert({
      where: { email: 'admin@acve.com' },
      update: {},
      create: {
        email: 'admin@acve.com',
        fullName: 'ACVE Admin',
        // ✅ CORRECT: Uses the strict Enum value
        role: UserRole.SUPER_ADMIN, 
        avatarUrl: 'https://github.com/shadcn.png',
      },
    })
    console.log(`👤 Created User: ${teacher.email}`)

    // 3. Create a Law Firm (B2B)
    const lawFirm = await prisma.company.create({
      data: {
        name: 'García & Partners',
        billingEmail: 'billing@garcia.com',
        maxSeats: 10,
        memberships: {
          create: {
            userId: teacher.id,
            // ✅ FIXED: Use 'ORG_ADMIN' to match your UserRole terminology
            // Since this field is a String in schema, we use the string value explicitly.
            role: 'ORG_ADMIN', 
          },
        },
      },
    })
    console.log(`🏢 Created Law Firm: ${lawFirm.name}`)

    // 4. Create the Bilingual Course (Contract Law)
    const course = await prisma.course.create({
      data: {
        title: {
          en: "Legal English: Contract Basics",
          es: "Inglés Jurídico: Fundamentos de Contratos"
        },
        slug: "contract-law-101",
        description: {
          en: "Master the terminology of international contracts.",
          es: "Domina la terminología de contratos internacionales."
        },
        level: ProficiencyLevel.INTERMEDIATE,
        status: ContentStatus.PUBLISHED,
        price: 499.00,
        authorId: teacher.id,
        tags: ["contracts", "civil law", "compliance"],

        modules: {
          create: {
            title: { en: "Module 1: Offer and Acceptance", es: "Módulo 1: Oferta y Aceptación" },
            orderIndex: 1,
            lessons: {
              create: {
                title: { en: "The Elements of a Contract", es: "Los Elementos de un Contrato" },
                slug: "elements-of-contract",
                orderIndex: 1,
                estimatedDuration: 600,
                isFreePreview: true,
                exercises: {
                  create: {
                    type: ExerciseType.MULTIPLE_CHOICE,
                    orderIndex: 1,
                    content: {
                      question: "What is 'Consideration' in a contract?",
                      options: ["Payment", "Thoughtfulness", "A value exchange", "A signature"],
                      correctAnswer: "A value exchange"
                    }
                  }
                }
              }
            }
          }
        }
      },
    })
    console.log(`📚 Created Course: ${course.slug}`)
    
    console.log('✅ Seed complete!')

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

main()