import { fileURLToPath } from 'url'
import { dirname, join } from 'path'
import nuxtPkg from 'nuxt/package.json'
import harmonicSaaSPkg from './package.json'

const currentDir = dirname(fileURLToPath(import.meta.url))

export default defineNuxtConfig({
  modules: [
    '@nuxt/eslint',
    ...(process.env.NODE_ENV !== 'production' ? ['@nuxt/test-utils/module'] : []),
    '@nuxt/ui',
    '@nuxtjs/i18n',
    '@vueuse/nuxt',
    'nuxt-email-renderer',
    join(currentDir, './app/modules/saasConfig')
  ],

  imports: {
    dirs: [
      join(currentDir, './app/composables'),
      join(currentDir, './app/utils')
    ]
  },

  devtools: { enabled: process.env.NODE_ENV !== 'production' },

  css: [
    join(currentDir, './app/assets/main.css')
  ],

  runtimeConfig: {
    // Nuxt automatically reads env vars and replaces these at runtime
    // Empty strings as defaults allow the app to start even if not set
    // Better Auth and other services will fail gracefully with helpful errors

    // Database
    databaseUrl: process.env.NUXT_DATABASE_URL || '',

    // Better Auth
    betterAuthSecret: process.env.NUXT_BETTER_AUTH_SECRET || '',
    betterAuthUrl: process.env.NUXT_BETTER_AUTH_URL || '', // Server-side base URL for Better Auth

    // Blob storage
    blobReadWriteToken: process.env.BLOB_READ_WRITE_TOKEN || '',

    // Storage provider configuration
    // Options: 'vercel-blob' (default), 'fly-io', 'custom'
    storageProvider: (process.env.STORAGE_PROVIDER as 'vercel-blob' | 'fly-io' | 'custom') || 'vercel-blob',

    // Fly.io (Tigris) storage configuration
    // Required when storageProvider is 'fly-io'
    flyStorageAccessKeyId: process.env.FLY_STORAGE_ACCESS_KEY_ID || '',
    flyStorageSecretAccessKey: process.env.FLY_STORAGE_SECRET_ACCESS_KEY || '',
    flyStorageEndpoint: process.env.FLY_STORAGE_ENDPOINT || '',
    flyStorageRegion: 'auto',
    flyStorageBucketName: process.env.FLY_STORAGE_BUCKET_NAME || '',
    flyStoragePublicUrlBase: process.env.FLY_STORAGE_PUBLIC_URL_BASE || '', // Optional: Custom public URL base for serving files

    // OAuth providers
    githubClientId: process.env.NUXT_GITHUB_CLIENT_ID || '',
    githubClientSecret: process.env.NUXT_GITHUB_CLIENT_SECRET || '',
    googleClientId: process.env.NUXT_GOOGLE_CLIENT_ID || '',
    googleClientSecret: process.env.NUXT_GOOGLE_CLIENT_SECRET || '',

    // Email service (Resend)
    // If not set, emails will be logged to console in development mode
    resendApiKey: process.env.NUXT_RESEND_API_KEY || '',
    fromEmail: process.env.NUXT_FROM_EMAIL || '',
    appName: process.env.NUXT_APP_NAME || '',
    mockEmail: process.env.NUXT_MOCK_EMAIL || '', // Set to 'true' to mock emails and log them with console.table

    // SMTP Configuration (for E2E testing with Mailpit)
    smtpHost: process.env.NUXT_SMTP_HOST || '',
    smtpPort: process.env.NUXT_SMTP_PORT || '',
    smtpSecure: process.env.NUXT_SMTP_SECURE || '',
    smtpUser: process.env.NUXT_SMTP_USER || '',
    smtpPassword: process.env.NUXT_SMTP_PASSWORD || '',

    // Stripe (only required if using Stripe integration)
    stripeSecretKey: process.env.NUXT_STRIPE_SECRET_KEY || '',
    stripeWebhookSecret: process.env.NUXT_STRIPE_WEBHOOK_SECRET || '',

    // Pusher Beams (for push notifications)
    // Only required if enablePushNotifications is true
    pusherBeamsInstanceId: process.env.PUSHER_BEAMS_INSTANCE_ID || '',
    pusherBeamsSecretKey: process.env.PUSHER_BEAMS_SECRET_KEY || '',

    public: {
      harmonicSaaSVersion: harmonicSaaSPkg.version,
      nuxtVersion: nuxtPkg.version,
      appLogTag: 'HarmonicSaaS', // Default tag, apps can override

      // Client-side base URL for Better Auth
      betterAuthUrl: process.env.NUXT_BETTER_AUTH_URL || '',
      auth: {
        redirectUserTo: '/dashboard',
        redirectGuestTo: '/auth'
      },
      // Base URL for API calls - will be set at runtime in Capacitor
      backendApiBaseUrl: process.env.NUXT_PUBLIC_BACKEND_API_BASE_URL || '',

      // Pusher configuration for real-time notifications (Vercel/Capacitor compatible)
      pusherKey: process.env.NUXT_PUBLIC_PUSHER_KEY || '',
      pusherCluster: process.env.NUXT_PUBLIC_PUSHER_CLUSTER || 'eu',

      // Pusher Beams instance ID for push notifications
      // Only used if enablePushNotifications is true
      pusherBeamsInstanceId: process.env.NUXT_PUBLIC_PUSHER_BEAMS_INSTANCE_ID || ''
    }
  },

  devServer: {
    cors: { origin: '*' }
  },

  compatibilityDate: '2025-11-25',

  nitro: {
    experimental: {
      tasks: true
    },
    // Fix for bundling conflicts in Docker builds (e.g., "gt symbol already declared")
    // Prevents Nitro from inlining packages that cause duplicate symbol declarations
    externals: {
      inline: []
    },
    routeRules: {
      '/api/**': {
        cors: true
        // Note: CORS headers are handled by server/middleware/cors.ts
        // to properly support credentials and Capacitor origins
      }
    }
  },

  vite: {
    optimizeDeps: {
      exclude: ['postgres', 'drizzle-orm', 'drizzle-orm/postgres-js', 'nodemailer']
    },
    // Mark Node.js-only packages as external for SSR
    ssr: {
      external: ['nodemailer', 'pusher', '@pusher/push-notifications-server']
    },
    build: {
      rollupOptions: {
        external: ['postgres', 'drizzle-orm']
      }
    },
    server: {
      allowedHosts: true,
      cors: { origin: '*' }
    }
  },

  eslint: {
    config: {
      stylistic: {
        commaDangle: 'never',
        braceStyle: '1tbs'
      }
    }
  },

  i18n: {
    detectBrowserLanguage: {
      useCookie: true,
      redirectOn: 'root'
    },
    locales: [
      { code: 'nl', name: 'Nederlands', iso: 'nl-BE', files: ['nl-text.json', 'nl-menus.json'] },
      { code: 'en', name: 'English', iso: 'en-US', files: ['en-text.json', 'en-menus.json'] }
    ],
    defaultLocale: 'nl',
    strategy: 'prefix_except_default'
  },

  saas: {
    enableMagicLink: true,
    enableOrganizations: false
  }
})
