import path from 'path';

export default ({ env }) => {
  const client = env('DATABASE_CLIENT', 'sqlite');

  console.log('=== DATABASE CONFIGURATION ===');
  console.log('DATABASE_CLIENT:', client);
  console.log('DATABASE_HOST:', env('DATABASE_HOST', 'not-set'));
  console.log('DATABASE_PORT:', env('DATABASE_PORT', 'not-set'));
  console.log('DATABASE_USERNAME:', env('DATABASE_USERNAME', 'not-set'));
  console.log('DATABASE_NAME:', env('DATABASE_NAME', 'not-set'));
  console.log('DATABASE_PASSWORD:', env('DATABASE_PASSWORD') ? '***SET***' : '***NOT SET***');
  console.log('DATABASE_SSL:', env('DATABASE_SSL', 'not-set'));

  if (client === 'postgres') {
    const connectionConfig = {
      host: env('DATABASE_HOST', 'localhost'),
      port: env.int('DATABASE_PORT', 5432),
      database: env('DATABASE_NAME', 'strapi'),
      user: env('DATABASE_USERNAME', 'strapi'),
      password: env('DATABASE_PASSWORD', 'strapi'),
      ssl: env.bool('DATABASE_SSL', false) ? { rejectUnauthorized: false } : false,
    };
    
    console.log('PostgreSQL connection config:', JSON.stringify({
      ...connectionConfig,
      password: connectionConfig.password ? `***${connectionConfig.password.length} chars***` : '***NOT SET***'
    }, null, 2));
    
    return {
      connection: {
        client: 'postgres',
        connection: connectionConfig,
        pool: {
          min: env.int('DATABASE_POOL_MIN', 2),
          max: env.int('DATABASE_POOL_MAX', 10),
        },
        acquireConnectionTimeout: env.int('DATABASE_TIMEOUT', 60000),
      },
    };
  }

  console.log('Using SQLite configuration');
  return {
    connection: {
      client: 'sqlite',
      connection: {
        filename: path.join(__dirname, '..', '..', env('DATABASE_FILENAME', '.tmp/data.db')),
      },
      useNullAsDefault: true,
    },
  };
};
