import { createDbClient, type DbClient } from '@banatie/database';
import { config } from 'dotenv';
import path from 'path';
import { existsSync } from 'fs';

// Load .env from api-service directory only if exists and not in Docker
// In Docker (IS_DOCKER=true), environment variables are injected via docker-compose
const envPath = path.join(__dirname, '../.env');
if (existsSync(envPath) && !process.env['IS_DOCKER']) {
  config({ path: envPath });
}

// Also load secrets.env if exists (for both dev and docker)
const secretsPath = path.join(__dirname, '../secrets.env');
if (existsSync(secretsPath)) {
  config({ path: secretsPath });
}

const DATABASE_URL =
  process.env['DATABASE_URL'] ||
  'postgresql://banatie_user:banatie_secure_password@localhost:5460/banatie_db';

export const db: DbClient = createDbClient(DATABASE_URL);

console.log(
  `[${new Date().toISOString()}] Database client initialized - ${new URL(DATABASE_URL).host}`,
);
