/**
 * Azure Cosmos DB client singleton.
 *
 * Reads COSMOS_ENDPOINT, COSMOS_KEY, and COSMOS_DATABASE from process.env.
 * Provides getCosmosClient(), getDatabase(), and getContainer() for simple usage.
 */

import { Container, CosmosClient, Database } from '@azure/cosmos';

let _client: CosmosClient | null = null;
let _database: Database | null = null;

function getEnvOrThrow(name: string): string {
  const value = process.env[name];
  if (!value) {
    throw new Error(`Environment variable ${name} is required`);
  }
  return value;
}

export function getCosmosClient(): CosmosClient {
  if (!_client) {
    _client = new CosmosClient({
      endpoint: getEnvOrThrow('COSMOS_ENDPOINT'),
      key: getEnvOrThrow('COSMOS_KEY'),
    });
  }
  return _client;
}

export function getDatabase(): Database {
  if (!_database) {
    const dbId = process.env.COSMOS_DATABASE || 'lysnrai';
    _database = getCosmosClient().database(dbId);
  }
  return _database;
}

/**
 * Get a container by name. Uses the singleton database.
 * For simple services that don't need a container registry.
 */
export function getContainer(name: string): Container {
  return getDatabase().container(name);
}

/**
 * Reset the singleton (useful for testing).
 * @internal
 */
export function _resetClient(): void {
  _client = null;
  _database = null;
}
