const RewardAuditLog = require('../models/RewardAuditLog');
const persistentStore = require('./persistentStore');

function getState() {
  return persistentStore.readState();
}

function normalizeIdentity(identity = {}) {
  if (!identity || typeof identity !== 'object') return null;
  return {
    serviceName: identity.serviceName || '',
    authenticated: Boolean(identity.authenticated),
    authMode: identity.authMode || ''
  };
}

function recordAccepted({ payload = {}, validation = null, reward = null, serviceIdentity = null } = {}) {
  const state = getState();
  const rows = Array.isArray(state.rewardAuditEntries) ? state.rewardAuditEntries : [];
  const audit = new RewardAuditLog({
    sourceService: payload.sourceService || validation?.sourceService || serviceIdentity?.serviceName || 'UNKNOWN',
    actionType: payload.actionType || payload.eventType || validation?.actionType || 'UNSPECIFIED',
    category: payload.category || payload.pointCategory || validation?.category || 'ecosystem',
    actorId: payload.actorId || payload.userId || payload.nodeId || null,
    idempotencyKey: payload.idempotencyKey || '',
    refId: payload.refId || payload.eventKey || payload.pointProofHash || '',
    rewardId: reward?.id || null,
    requestHash: RewardAuditLog.hashRequest(payload),
    validation,
    serviceIdentity: normalizeIdentity(serviceIdentity),
    status: 'accepted',
    metadata: {
      rewardAmount: Number(reward?.rewardAmount || 0),
      rewardScore: Number(reward?.rewardScore || 0),
      rewardMode: reward?.mode || '',
      rewardFlags: reward?.flags || []
    }
  });
  rows.unshift(audit);
  state.rewardAuditEntries = rows;
  persistentStore.writeState(state);
  return audit;
}

function listEntries() {
  return Array.isArray(getState().rewardAuditEntries) ? getState().rewardAuditEntries : [];
}

function findEntry(value) {
  const key = String(value || '').trim();
  if (!key) return null;
  return listEntries().find((row) => (
    row.id === key ||
    row.requestHash === key ||
    row.idempotencyKey === key ||
    row.refId === key ||
    row.rewardId === key
  )) || null;
}

function getStats() {
  const entries = listEntries();
  return {
    entryCount: entries.length,
    acceptedCount: entries.filter(row => row.status === 'accepted').length,
    reviewCount: entries.filter(row => row.validation && row.validation.ok === false).length,
    latestEntries: entries.slice(0, 10)
  };
}

module.exports = {
  findEntry,
  getStats,
  listEntries,
  recordAccepted
};
