import { beforeAll, afterAll, beforeEach } from 'vitest'
import { prisma } from './src/lib/prisma'

// Integration tests require Docker Compose to be running
// Run: docker compose up -d
// The database should be accessible at localhost:5432

// Setup for integration tests
beforeAll(async () => {
  console.log('🔗 Connecting to test database...')

  // Check if DATABASE_URL is set
  if (!process.env.DATABASE_URL) {
    throw new Error(
      'DATABASE_URL is not set. Make sure Docker Compose is running and .env has DATABASE_URL'
    )
  }

  try {
    await prisma.$connect()
    console.log('✅ Connected to test database')
  } catch (error) {
    console.error('❌ Failed to connect to database. Is Docker Compose running?')
    console.error('   Run: docker compose up -d')
    throw error
  }
})

beforeEach(async () => {
  // Clean database before each test (in correct order due to foreign keys)
  await prisma.sessionReview.deleteMany()
  await prisma.learningSession.deleteMany()
  await prisma.collectionItem.deleteMany()
  await prisma.collection.deleteMany()
  await prisma.userHanziProgress.deleteMany()
  await prisma.account.deleteMany()
  await prisma.session.deleteMany()
  await prisma.verificationToken.deleteMany()
  await prisma.userPreference.deleteMany()
  await prisma.user.deleteMany()
  await prisma.hanziMeaning.deleteMany()
  await prisma.hanziTranscription.deleteMany()
  await prisma.hanziForm.deleteMany()
  await prisma.hanziHSKLevel.deleteMany()
  await prisma.hanziPOS.deleteMany()
  await prisma.hanziClassifier.deleteMany()
  await prisma.hanzi.deleteMany()
  await prisma.language.deleteMany()
})

afterAll(async () => {
  console.log('🔌 Disconnecting from test database...')
  await prisma.$disconnect()
})
