import { Options } from '@mikro-orm/core';
import { PostgreSqlDriver } from '@mikro-orm/postgresql';
import { Migrator } from '@mikro-orm/migrations';
import dotenv from 'dotenv';

// Load environment variables if not in Kubernetes
if (process.env.KUBERNETES_SERVICE_HOST === undefined) {
    dotenv.config({ override: true });
}

const isProduction = process.env.NODE_ENV === 'production';

// Validate required environment variables
const requiredEnvVars = ['POSTGRES_DB', 'POSTGRES_USER', 'POSTGRES_PASSWORD'];
const missingEnvVars = requiredEnvVars.filter(envVar => !process.env[envVar]);

if (missingEnvVars.length > 0 && isProduction) {
    throw new Error(`Missing required environment variables: ${missingEnvVars.join(', ')}`);
}

const config: Options = {
    driver: PostgreSqlDriver,
    entities: [
        './dist/src/apps/_app/entities/**/*.js',
        './dist/src/apps/canvas-api/entities/**/*.js',
    ],
    entitiesTs: [
        './src/apps/_app/entities/**/*.ts',
        './src/apps/canvas-api/entities/**/*.ts',
    ],
    extensions: [Migrator],
    baseDir: process.cwd(),
    discovery: {
        warnWhenNoEntities: true,
        disableDynamicFileAccess: false,
    },
    dbName: process.env.POSTGRES_DB || 'fusero-boilerplate-db',
    host: process.env.POSTGRES_HOSTNAME || 'localhost',
    port: Number(process.env.POSTGRES_PORT) || 5432,
    user: process.env.POSTGRES_USER || 'root',
    password: process.env.POSTGRES_PASSWORD || 'root123',
    debug: !isProduction,
    migrations: {
        tableName: process.env.POSTGRES_DB,
        path: isProduction ? './dist/src/database/migrations' : './src/database/migrations',
        glob: '!(*.d).{js,ts}',
        transactional: true,
        disableForeignKeys: true,
        allOrNothing: true,
        dropTables: true,
        safe: false,
        snapshot: true,
        emit: 'ts',
    },
    // Add connection pool settings
    pool: {
        min: 2,
        max: 10,
        idleTimeoutMillis: 30000,
        acquireTimeoutMillis: 30000,
    },
};

export default config;
