import sql from 'mssql';
import 'dotenv/config';

const config = {
  server: process.env.MSSQL_SERVER || 'localhost',
  port: Number(process.env.MSSQL_PORT) || 1433,
  database: process.env.MSSQL_DATABASE || 'eazybusiness',
  user: process.env.MSSQL_USER,
  password: process.env.MSSQL_PASSWORD,
  options: {
    encrypt: process.env.MSSQL_ENCRYPT !== 'false',
    trustServerCertificate: process.env.MSSQL_TRUST_SERVER_CERTIFICATE !== 'false',
  },
};

/** @type {sql.ConnectionPool | null} */
let pool = null;

export function getPool() {
  if (!pool) {
    throw new Error('MSSQL pool is not connected. Call connectDb() first.');
  }
  return pool;
}

export async function connectDb() {
  if (pool) {
    return pool;
  }

  if (!config.user) {
    throw new Error('MSSQL_USER is not set in environment');
  }

  pool = await sql.connect(config);
  return pool;
}

export async function closeDb() {
  if (pool) {
    await pool.close();
    pool = null;
  }
}

export async function pingDb() {
  const result = await getPool().request().query('SELECT 1 AS ok');
  return result.recordset[0]?.ok === 1;
}
