// Runtime environment validation (non-blocking)
// This app uses cloud services (Neon, Vercel Blob) even when deployed locally

interface EnvConfig {
  DATABASE_URL: string | undefined
  POSTGRES_URL: string | undefined
  BLOB_READ_WRITE_TOKEN: string | undefined
  JWT_SECRET: string | undefined
  hasDatabase: boolean
  hasBlob: boolean
}

export function validateEnv(): EnvConfig {
  const config: EnvConfig = {
    DATABASE_URL: process.env.DATABASE_URL,
    POSTGRES_URL: process.env.POSTGRES_URL,
    BLOB_READ_WRITE_TOKEN: process.env.BLOB_READ_WRITE_TOKEN,
    JWT_SECRET: process.env.JWT_SECRET,
    hasDatabase: !!(process.env.DATABASE_URL || process.env.POSTGRES_URL),
    hasBlob: !!process.env.BLOB_READ_WRITE_TOKEN,
  }

  const missing: string[] = []
  const warnings: string[] = []

  if (!config.hasDatabase) {
    missing.push("POSTGRES_URL or DATABASE_URL (Neon database)")
  }
  
  if (!config.hasBlob) {
    warnings.push("BLOB_READ_WRITE_TOKEN (file uploads will fail)")
  }

  if (!config.JWT_SECRET) {
    warnings.push("JWT_SECRET (using default - not secure for production)")
  }

  if (missing.length > 0) {
    console.error(`
========================================
[ENV] MISSING REQUIRED ENVIRONMENT VARIABLES
========================================
${missing.map(m => `- ${m}`).join('\n')}

This app requires a Neon PostgreSQL database to function.
Please copy .env.example to .env.local and configure your credentials.

For local deployment:
1. cp .env.example .env.local
2. Get POSTGRES_URL from your Vercel project or Neon dashboard
3. Restart the dev server
========================================
`)
  }

  if (warnings.length > 0) {
    console.warn(`[ENV] Warnings: ${warnings.join(", ")}`)
  }

  if (config.hasDatabase && config.hasBlob) {
    console.log("[ENV] All cloud services configured (Neon + Blob)")
  }

  return config
}

export const env = validateEnv()
