const path = require('path');
// Load .env from project root (two levels up from packages/hub)
const envPath = path.resolve(process.cwd(), '../../.env');
require('dotenv').config({ path: envPath });

/**
 * Parse DATABASE_URL into connection parameters
 */
function parseDatabaseUrl(url) {
  try {
    const parsed = new URL(url);

    if (parsed.protocol !== 'postgresql:' && parsed.protocol !== 'postgres:') {
      throw new Error(
        `Unsupported database protocol: ${parsed.protocol}. Expected postgresql:// or postgres://`
      );
    }

    const host = parsed.hostname || 'localhost';
    const port = parsed.port ? parseInt(parsed.port, 10) : 5432;
    const username = parsed.username || 'postgres';
    const password = decodeURIComponent(parsed.password || '');
    const database = parsed.pathname ? parsed.pathname.slice(1) : 'device_farm'; // Remove leading '/'

    return { host, port, username, password, database };
  } catch (error) {
    throw new Error(`Invalid DATABASE_URL: ${error.message}`);
  }
}

/**
 * Get database configuration from environment variables
 * Priority: DATABASE_URL > individual env vars > defaults
 */
function getDbConfig(defaultDatabase) {
  // If DATABASE_URL is provided, use it
  if (process.env.DATABASE_URL) {
    const parsed = parseDatabaseUrl(process.env.DATABASE_URL);
    // Override database name if provided as default
    if (defaultDatabase) {
      parsed.database = defaultDatabase;
    }
    return parsed;
  }

  // Otherwise, use individual environment variables with defaults
  return {
    host: process.env.DB_HOST || 'localhost',
    port: parseInt(process.env.DB_PORT || '5432', 10),
    username: process.env.DB_USER || 'postgres',
    password: process.env.DB_PASSWORD || '',
    database: defaultDatabase || process.env.DB_NAME || 'device_farm',
  };
}

module.exports = {
  'migrations-path': path.resolve(__dirname, '../../migrations'),
  'seeders-path': path.resolve(__dirname, '../../seeders'),
  'models-path': path.resolve(__dirname, '../db/models'),
  development: {
    ...getDbConfig('device_farm'),
    dialect: 'postgres',
    logging: process.env.DB_LOGGING === 'true' ? console.log : false,
  },
  test: {
    ...getDbConfig('device_farm_test'),
    dialect: 'postgres',
    logging: false,
  },
  production: {
    ...getDbConfig(process.env.DB_NAME),
    dialect: 'postgres',
    logging: false,
  },
};
