const MAX_RECENT_ERRORS = 10;

const state = {
  worker: {
    enabled: false,
    running: false,
    started_at: null,
    last_run_at: null,
    next_run_at: null,
    last_error: null,
  },
  notifications: {
    last_test_at: null,
    last_error: null,
  },
  recentErrors: [],
};

function toMessage(error) {
  if (!error) return null;
  if (typeof error === 'string') return error;
  return error.message || String(error);
}

function recordError(source, error) {
  const message = toMessage(error);
  if (!message) return;

  state.recentErrors.unshift({
    timestamp: new Date().toISOString(),
    source,
    message,
  });

  state.recentErrors = state.recentErrors.slice(0, MAX_RECENT_ERRORS);
}

function markWorkerStarted(nextRunAt = null) {
  state.worker.enabled = true;
  state.worker.running = true;
  state.worker.started_at = state.worker.started_at || new Date().toISOString();
  state.worker.next_run_at = nextRunAt;
}

function markWorkerSuccess(nextRunAt = null) {
  state.worker.last_run_at = new Date().toISOString();
  state.worker.last_error = null;
  if (nextRunAt !== undefined) state.worker.next_run_at = nextRunAt;
}

function markWorkerError(error, nextRunAt = null) {
  state.worker.last_run_at = new Date().toISOString();
  state.worker.last_error = toMessage(error);
  if (nextRunAt !== undefined) state.worker.next_run_at = nextRunAt;
  recordError('Daily Worker', error);
}

function markNotificationTestSuccess() {
  state.notifications.last_test_at = new Date().toISOString();
  state.notifications.last_error = null;
}

function markNotificationError(error) {
  state.notifications.last_error = toMessage(error);
  recordError('Notifications', error);
}

function markNotificationSuccess() {
  state.notifications.last_error = null;
}

function getStatusRuntime() {
  return {
    worker: { ...state.worker },
    notifications: { ...state.notifications },
    recentErrors: [...state.recentErrors],
  };
}

module.exports = {
  getStatusRuntime,
  markNotificationError,
  markNotificationSuccess,
  markNotificationTestSuccess,
  markWorkerError,
  markWorkerStarted,
  markWorkerSuccess,
  recordError,
};
