import "server-only";

function parseInteger(value: string | undefined, fallback: number) {
  if (!value) {
    return fallback;
  }

  const parsed = Number.parseInt(value, 10);
  return Number.isFinite(parsed) ? parsed : fallback;
}

function parseBoolean(value: string | undefined, fallback: boolean) {
  if (!value) {
    return fallback;
  }

  const normalized = value.trim().toLowerCase();

  if (["1", "true", "yes", "si"].includes(normalized)) {
    return true;
  }

  if (["0", "false", "no"].includes(normalized)) {
    return false;
  }

  return fallback;
}

export const licitationsConfig = {
  staleDaysThreshold: parseInteger(process.env.LICITATIONS_STALE_DAYS, 45),
  currentWindowDays: parseInteger(process.env.LICITATIONS_CURRENT_WINDOW_DAYS, 30),
  requestDelayMs: parseInteger(process.env.LICITATIONS_REQUEST_DELAY_MS, 750),
  maxRetries: parseInteger(process.env.LICITATIONS_MAX_RETRIES, 3),
  maxMunicipalitiesPerRun: parseInteger(process.env.LICITATIONS_MAX_MUNICIPALITIES_PER_RUN, 100),
  scrapingEnabledByDefault: parseBoolean(process.env.LICITATIONS_SCRAPING_ENABLED, true),
  syncCronToken: process.env.LICITATIONS_SYNC_TOKEN ?? "",
  licitayaEnabled: parseBoolean(process.env.LICITAYA_ENABLED, true),
  licitayaItemsPerPage: parseInteger(process.env.LICITAYA_ITEMS_PER_PAGE, 50),
  licitayaMaxPagesPerRun: parseInteger(process.env.LICITAYA_MAX_PAGES_PER_RUN, 3),
  licitayaSyncIntervalHours: parseInteger(process.env.LICITAYA_SYNC_INTERVAL_HOURS, 12),
  licitayaDateOffsetDays: parseInteger(process.env.LICITAYA_DATE_OFFSET_DAYS, 1),
  licitayaDateFallbackWindowDays: parseInteger(process.env.LICITAYA_DATE_FALLBACK_WINDOW_DAYS, 3),
  licitayaTimeoutMs: parseInteger(process.env.LICITAYA_TIMEOUT_MS, 20000),
  cronSecret: process.env.CRON_SECRET ?? "",
};
