// Environment variable validation and type-safe access
const requiredEnvVars = {
  DATABASE_URL: process.env.DATABASE_URL || process.env.POSTGRES_URL,
  BLOB_READ_WRITE_TOKEN: process.env.BLOB_READ_WRITE_TOKEN,
} as const

const optionalEnvVars = {
  JWT_SECRET: process.env.JWT_SECRET || "dev-secret-change-in-production",
  NEXT_PUBLIC_APP_URL: process.env.NEXT_PUBLIC_APP_URL || "http://localhost:3000",
  NEXT_PUBLIC_API_URL: process.env.NEXT_PUBLIC_API_URL || "http://localhost:3000/api",
  ENABLE_DOWNLOADS: process.env.ENABLE_DOWNLOADS !== "false",
  ENABLE_OFFLINE: process.env.ENABLE_OFFLINE !== "false",
  ENABLE_SOCIAL_LOGIN: process.env.ENABLE_SOCIAL_LOGIN === "true",
} as const

// Validate required environment variables
function validateEnv() {
  const missing: string[] = []

  for (const [key, value] of Object.entries(requiredEnvVars)) {
    if (!value) {
      missing.push(key)
    }
  }

  if (missing.length > 0 && process.env.NODE_ENV === "production") {
    throw new Error(`Missing required environment variables:\n${missing.join("\n")}\n\nPlease check your .env file.`)
  }

  if (missing.length > 0) {
    console.warn("[ENV] Missing environment variables (using defaults for development):", missing)
  }
}

// Run validation
if (typeof window === "undefined") {
  validateEnv()
}

export const env = {
  ...requiredEnvVars,
  ...optionalEnvVars,
} as const

export function isDevelopment() {
  return process.env.NODE_ENV === "development"
}

export function isProduction() {
  return process.env.NODE_ENV === "production"
}
