import { mkdir } from 'fs/promises'
import { existsSync } from 'fs'
import { join } from 'path'

export default defineNitroPlugin(async (nitroApp) => {
  console.log('[STARTUP] Server-side initialization starting...')
  
  try {
    // Ensure data directories exist
    const dataDir = './data'
    const oidcSessionsDir = './data/oidc-sessions'
    const sessionsDir = './data/sessions'
    
    console.log('[STARTUP] Checking storage directories...')
    
    // Create directories if they don't exist
    const dirs = [dataDir, oidcSessionsDir, sessionsDir]
    for (const dir of dirs) {
      if (!existsSync(dir)) {
        console.log(`[STARTUP] Creating directory: ${dir}`)
        await mkdir(dir, { recursive: true })
        console.log(`[STARTUP] Successfully created: ${dir}`)
      } else {
        console.log(`[STARTUP] Directory exists: ${dir}`)
      }
    }
    
    // Check environment variables
    console.log('[STARTUP] Checking OIDC environment variables...')
    const requiredEnvVars = [
      'NUXT_OIDC_TOKEN_KEY',
      'NUXT_OIDC_SESSION_SECRET', 
      'NUXT_OIDC_AUTH_SESSION_SECRET',
      'NUXT_OIDC_PROVIDERS_KEYCLOAK_CLIENT_SECRET'
    ]
    
    for (const envVar of requiredEnvVars) {
      const value = process.env[envVar]
      if (value) {
        console.log(`[STARTUP] ✅ ${envVar}: present (length: ${value.length})`)
      } else {
        console.error(`[STARTUP] ❌ ${envVar}: MISSING`)
      }
    }
    
    console.log('[STARTUP] Server-side initialization complete')
    
  } catch (error) {
    console.error('[STARTUP] Server-side initialization error:', error)
    // Don't throw - let the app continue with fallback behavior
  }
})
