const Redis = require('ioredis');
const { Pool } = require('pg');
const env = require('./env');
const logger = require('../utils/logger');

const redis = new Redis(env.redisUrl, {
  lazyConnect: true,
  maxRetriesPerRequest: null
});

const pgPool = new Pool({
  host: env.postgres.host,
  port: env.postgres.port,
  database: env.postgres.database,
  user: env.postgres.user,
  password: env.postgres.password,
  idleTimeoutMillis: 30_000
});

const warmupInfrastructure = async () => {
  const state = { redis: false, postgres: false };

  try {
    if (!redis.status || redis.status === 'end') {
      await redis.connect();
    }
    await redis.ping();
    state.redis = true;
  } catch (error) {
    logger.warn(`[redis] baglanti hazir degil: ${error.message}`);
  }

  try {
    const client = await pgPool.connect();
    await client.query('SELECT 1');
    client.release();
    state.postgres = true;
  } catch (error) {
    logger.warn(`[postgres] baglanti hazir degil: ${error.message}`);
  }

  return state;
};

module.exports = {
  redis,
  pgPool,
  warmupInfrastructure
};
