/**
 * Database configuration utilities
 * Supports both DATABASE_URL and individual environment variables
 */

export interface ParsedDbConfig {
  host: string;
  port: number;
  user: string;
  username: string;
  password: string;
  database: string;
}

/**
 * Parse DATABASE_URL into connection parameters
 * Supports formats:
 * - postgresql://user:password@host:port/database
 * - postgres://user:password@host:port/database
 */
export function parseDatabaseUrl(url: string): ParsedDbConfig {
  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 user = parsed.username || 'postgres';
    const password = decodeURIComponent(parsed.password || '');
    const database = parsed.pathname ? parsed.pathname.slice(1) : 'device_farm'; // Remove leading '/'

    return {
      host,
      port,
      user,
      username: user, // Sequelize uses 'username', pg Client uses 'user'
      password,
      database,
    };
  } catch (error) {
    throw new Error(
      `Invalid DATABASE_URL: ${error instanceof Error ? error.message : String(error)}`
    );
  }
}

/**
 * Get database configuration from environment variables
 * Priority: DATABASE_URL > individual env vars > defaults
 */
export function getDbConfig(): ParsedDbConfig {
  // If DATABASE_URL is provided, use it
  if (process.env.DATABASE_URL) {
    return parseDatabaseUrl(process.env.DATABASE_URL);
  }

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

/**
 * Get database name from environment variables
 * Extracts from DATABASE_URL if present, otherwise uses DB_NAME
 */
export function getDbName(): string {
  if (process.env.DATABASE_URL) {
    const config = parseDatabaseUrl(process.env.DATABASE_URL);
    return config.database;
  }
  return process.env.DB_NAME || 'device_farm';
}
