'use strict';

const { loadState, updateState } = require('./agentState');

function getWatermark(entityType) {
  return loadState().watermarks?.[entityType] || null;
}

function setWatermark(entityType, watermark) {
  updateState((state) => {
    state.watermarks = state.watermarks || {};
    state.watermarks[entityType] = watermark;
    return state;
  });
}

function scopeKey(config = {}) {
  return [config.sourceSystem || 'softrestaurant', config.tenantId || '', config.branchId || ''].join(':');
}

function ensureWatermarkScope(config = {}) {
  const nextScope = scopeKey(config);
  if (!config.tenantId || !config.branchId) return { changed: false, scope: nextScope };
  let result = { changed: false, scope: nextScope };
  updateState((state) => {
    if (state.watermarkScope === nextScope) return state;
    const previousScope = state.watermarkScope || null;
    const previousWatermarks = state.watermarks || {};
    const hadWatermarks = Object.keys(previousWatermarks).length > 0;
    if (hadWatermarks) {
      state.watermarkHistory = Array.isArray(state.watermarkHistory) ? state.watermarkHistory.slice(-2) : [];
      state.watermarkHistory.push({ scope: previousScope, archivedAt: new Date().toISOString(), watermarks: previousWatermarks });
      const days = Math.min(365, Math.max(7, Number(process.env.ARKHON_INITIAL_HISTORY_DAYS || 90)));
      const cutoff = new Date(Date.now() - days * 86400000).toISOString();
      const transactional = new Set(['sales', 'sale_items', 'sale_payments', 'cuts', 'cancellations', 'cash_movements', 'open_table_sessions']);
      state.watermarks = {};
      for (const entityType of transactional) state.watermarks[entityType] = cutoff;
    }
    state.watermarkScope = nextScope;
    state.watermarkScopeChangedAt = new Date().toISOString();
    result = { changed: previousScope !== null || hadWatermarks, scope: nextScope, previousScope };
    return state;
  });
  return result;
}

module.exports = { getWatermark, setWatermark, scopeKey, ensureWatermarkScope };
