import { LogLevel } from '@pikku/core/services'
import { globalBundlePem } from '../config/global-bundle.js'

import type {
  SecretService,
  VariablesService,
} from '@pikku/core/services'
import { pikkuConfig } from '#pikku/pikku-types.gen.js'
import { LOCAL_SQLITE_DB } from './local-db.js'

export interface SQLConfig {
  ssl?: {
    rejectUnauthorized: boolean
    ca: string
  }
}

const { DOMAIN } = process.env

const requireInProduction = (value: string | undefined, name: string) => {
  if (process.env.NODE_ENV === 'production' && !value) {
    throw new Error(`${name} must be configured in production`)
  }

  return value
}

export const createConfig = pikkuConfig(async (variablesService) => ({
  domain: requireInProduction(DOMAIN, 'DOMAIN') || 'localhost:3001',
  sqliteDb: process.env.SQLITE_DB || LOCAL_SQLITE_DB,
  port: 4002,
  hostname: '0.0.0.0',
  logLevel: LogLevel.info,
  content: {
    localFileUploadPath: process.env.CONTENT_LOCAL_FILE_UPLOAD_PATH || '../../.uploads',
    uploadUrlPrefix:
      process.env.CONTENT_UPLOAD_URL_PREFIX ||
      `${(process.env.API_ORIGIN || (DOMAIN ? `https://api.${DOMAIN}` : 'http://localhost:3000')).replace(/\/$/, '')}/reaper/`,
    assetUrlPrefix: process.env.CONTENT_ASSET_URL_PREFIX || '/assets',
    server:
      process.env.CONTENT_SERVER ||
      process.env.API_ORIGIN ||
      (DOMAIN ? `https://api.${DOMAIN}` : 'http://localhost:3000'),
  },
  secrets: {
    mailgunApiKey: 'MAILGUN_API_KEY'
  },
  sql: {
    ssl: variablesService?.get('NODE_ENV') === 'production' ? {
      rejectUnauthorized: true,
      ca: globalBundlePem
    } : undefined
  },
  apiKeys:
    process.env.API_KEYS?.split(',')
      .map((key) => key.trim())
      .filter(Boolean) ||
    (process.env.NODE_ENV === 'production' ? [] : ['dev-api-key']),
}))
