'use strict';

const storage = require('../storage');
const { isWriteEnabled } = require('../../../agent/softrestaurant-bridge/writers');
const { assertSafeEvent } = require('../../../agent/softrestaurant-bridge/security/payload-security');

function applyToMirror(event) {
  assertSafeEvent(event);
  if (event.event_type === 'STOCK_SNAPSHOT_RECORDED' && event.entity_type !== 'stock_snapshot') {
    throw Object.assign(new Error('STOCK_SNAPSHOT_RECORDED solo puede actualizar stock_snapshot observacional'), { code: 'INVALID_STOCK_SNAPSHOT_ENTITY' });
  }
  let details = {};
  storage.update('mirror', {}, (mirror) => {
    const key = `${event.entity_type}:${event.entity_id}`;
    const current = mirror[key];
    if (current && new Date(current.source_updated_at).getTime() > new Date(event.source_updated_at).getTime()) {
      details = { result: 'ignored_stale', application: 'ignored_stale', softrestaurant_write_enabled: false };
      return mirror;
    }
    mirror[key] = {
      event_id: event.event_id,
      entity_type: event.entity_type,
      entity_id: event.entity_id,
      canonical: event.payload_json?.canonical || event.payload_json,
      payload_hash: event.payload_hash,
      source_updated_at: event.source_updated_at,
      applied_at: new Date().toISOString(),
    };
    details = { result: 'ok', application: 'applied_to_local_mirror', softrestaurant_write_enabled: false };
    return mirror;
  });
  return details;
}

async function apply(event) {
  if (isWriteEnabled()) {
    throw Object.assign(new Error('La escritura SoftRestaurant no esta implementada en esta fase'), { code: 'SOFTRESTAURANT_WRITER_NOT_IMPLEMENTED' });
  }
  return applyToMirror(event);
}

module.exports = { apply, applyToMirror };
