'use strict';

// ARKHON — manejo de fecha/hora local para SoftRestaurant.
// SoftRestaurant/SQL Server guardan DATETIME en hora local del restaurante.
// ARKHON no debe restar/sumar UTC manualmente para mostrar fechas reales.

const TZ_OFFSET = 0; // Compatibilidad con código anterior; sin ajuste manual.
let _sqlDateCache = null;
let _sqlDateTs = 0;
const SQL_DATE_TTL = 5 * 60 * 1000;

function pad(n) { return String(n).padStart(2, '0'); }

async function getSqlToday(pool) {
  const now = Date.now();
  if (_sqlDateCache && (now - _sqlDateTs) < SQL_DATE_TTL) return _sqlDateCache;
  try {
    const r = await pool.request().query(`SELECT CONVERT(VARCHAR(10), GETDATE(), 120) AS hoy`);
    _sqlDateCache = r.recordset[0].hoy;
    _sqlDateTs = now;
    return _sqlDateCache;
  } catch (_) {
    return localDateStr();
  }
}

function localNow() { return new Date(); }
function localDateStr(date = new Date()) {
  const d = new Date(date);
  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
}
function localYesterday() { const d = new Date(); d.setDate(d.getDate() - 1); return localDateStr(d); }
function localYear()  { return new Date().getFullYear(); }
function localMonth() { return new Date().getMonth() + 1; }
function localHour()  { return new Date().getHours(); }
function toLocalTimeStr(date) {
  if (!date) return null;
  const d = new Date(date);
  return `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
}
function toLocalISOStr(date) {
  if (!date) return null;
  const d = new Date(date);
  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
}
function toSqlDateTimeStr(date) { return toLocalISOStr(date)?.replace('T', ' '); }

module.exports = {
  localDateStr, localYesterday, localYear, localMonth,
  localNow, localHour, toLocalTimeStr, toLocalISOStr, toSqlDateTimeStr,
  TZ_OFFSET, getSqlToday,
};
