import '@testing-library/jest-dom'
import { vi, beforeAll, afterAll, beforeEach } from 'vitest'

// Check if we have test database credentials
const hasTestDb = process.env.NEXT_PUBLIC_SUPABASE_URL && 
                  (process.env.SUPABASE_SERVICE_ROLE_KEY || process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY)

// Global test setup
beforeAll(async () => {
  if (hasTestDb) {
    console.log('🧪 Setting up test environment with real database...')
    const testUrl = process.env.NEXT_PUBLIC_SUPABASE_URL
    if (!testUrl?.includes('test') && !testUrl?.includes('localhost')) {
      console.warn('⚠️  WARNING: Not using a test database!')
      console.warn('Current URL:', testUrl)
    }
  } else {
    console.log('🧪 Running tests with mocked database...')
  }
})

beforeEach(async () => {
  // Cleanup before each test to ensure isolation (only if we have real DB)
  if (hasTestDb) {
    try {
      const { cleanupTestData } = await import('./helpers')
      await cleanupTestData()
    } catch (e) {
      // Silently ignore if helpers not available
    }
  }
})

afterAll(async () => {
  if (hasTestDb) {
    console.log('🧹 Cleaning up test environment...')
    try {
      const { cleanupTestData } = await import('./helpers')
      await cleanupTestData()
    } catch (e) {
      // Silently ignore if helpers not available
    }
  }
})

// Mock Supabase client for component tests that don't need real DB
vi.mock('@/lib/supabase', () => ({
  supabase: {
    storage: {
      from: vi.fn(() => ({
        upload: vi.fn(),
        remove: vi.fn(),
        move: vi.fn(),
        list: vi.fn(),
        getPublicUrl: vi.fn(() => ({ data: { publicUrl: 'https://example.com/test.jpg' } })),
      })),
    },
  },
}))
