// Data-import DOMAIN — Cloud Import reducer (pure transition function). Source: §4:125-133.
// Validation (parseItemsList — C2/C5) and task creation (C3/C4) are performed by the application
// use-case, which dispatches VALIDATE_OK/FAIL and TASKS_CREATED/IMPORT_FAIL back in.

import type { CloudEvent, CloudMachine } from './states';

export function cloudReducer(m: CloudMachine, e: CloudEvent): CloudMachine {
  const { state, context } = m;

  switch (e.type) {
    case 'STORAGE_VERIFIED':
      // C1 — a verified storage method (or 'public') makes storage ready.
      if (state !== 'StorageNotReady' && state !== 'StorageReady') return m;
      return { state: 'StorageReady', context: { ...context, storageMethodId: e.storageMethodId } };

    case 'RESET_STORAGE':
      return { state: 'StorageNotReady', context: { ...context, storageMethodId: null } };

    case 'PREPARE_LIST':
      if (state !== 'StorageReady' && state !== 'PreparingItemsList') return m;
      return { state: 'PreparingItemsList', context };

    case 'SET_ITEMS_LIST':
      if (state !== 'PreparingItemsList') return m;
      return { ...m, context: { ...context, itemsListJson: e.json, errors: [] } };

    case 'IMPORT_DATA':
      if (state !== 'PreparingItemsList') return m;
      return { state: 'ValidatingList', context: { ...context, errors: [] } };

    case 'VALIDATE_OK':
      if (state !== 'ValidatingList') return m;
      return { state: 'CreatingTasks', context: { ...context, tasks: e.tasks, errors: [] } };

    case 'VALIDATE_FAIL':
      // C2/C5 failure → back to editing with per-entry errors.
      if (state !== 'ValidatingList') return m;
      return { state: 'PreparingItemsList', context: { ...context, errors: e.errors } };

    case 'TASKS_CREATED':
      // C3/C4 — referencing tasks created, no data copied.
      if (state !== 'CreatingTasks') return m;
      return { state: 'Complete', context: { ...context, createdTaskIds: e.taskIds, errors: [] } };

    case 'IMPORT_FAIL':
      if (state !== 'CreatingTasks') return m;
      return { state: 'ImportError', context: { ...context, errors: e.errors ?? context.errors } };

    case 'RETRY':
      if (state === 'ImportError') return { ...m, state: 'CreatingTasks' };
      return m;

    default:
      return m;
  }
}
