const sql = require('mssql');

let poolPromise;

function boolFromEnv(value, fallback) {
  if (value === undefined || value === null || value === '') return fallback;
  return ['1', 'true', 'yes'].includes(String(value).toLowerCase());
}

function getConfig() {
  return {
    server: process.env.SQLSERVER_HOST || 'localhost',
    port: Number(process.env.SQLSERVER_PORT || 1433),
    database: process.env.SQLSERVER_DATABASE || 'RobotInstaller',
    user: process.env.SQLSERVER_USER,
    password: process.env.SQLSERVER_PASSWORD,
    options: {
      encrypt: boolFromEnv(process.env.SQLSERVER_ENCRYPT, false),
      trustServerCertificate: boolFromEnv(process.env.SQLSERVER_TRUST_SERVER_CERTIFICATE, true),
      useUTC: boolFromEnv(process.env.SQLSERVER_USE_UTC, true)
    },
    pool: {
      max: 10,
      min: 0,
      idleTimeoutMillis: 30000
    }
  };
}

async function getPool() {
  if (!poolPromise) {
    poolPromise = sql.connect(getConfig());
  }

  return poolPromise;
}

async function closePool() {
  if (!poolPromise) return;

  const pool = await poolPromise;
  await pool.close();
  poolPromise = undefined;
}

module.exports = {
  sql,
  getPool,
  closePool
};
