// Data-import DOMAIN — Cloud Import state machine: States, Events, Context. Pure.
// Source: docs/workflows/data-import-spec.md §4 (§4:125-133 transitions + guards C1-C6) and
// items-list-spec.md (the Items List is authoritative for task boundaries — MAP4/C3).
//
// [DESIGN] note: §4's transient `ImportingList` state (uploading the JSON) is folded into the
// IMPORT_DATA -> ValidatingList edge — for a client-authored Items List the "upload" is
// instantaneous, so a distinct ImportingList state would never be observably entered.

import type { ImportError } from '../types';
import type { ItemsListTask } from '../itemsList/parse';

export type CloudState =
  | 'StorageNotReady'
  | 'StorageReady'
  | 'PreparingItemsList'
  | 'ValidatingList'
  | 'CreatingTasks'
  | 'Complete'
  | 'ImportError';

export interface CloudContext {
  /** A *verified* StorageMethod id (C1), or the literal 'public'. Null until storage is chosen. */
  storageMethodId: string | null;
  /** The authored/uploaded Items List JSON text. */
  itemsListJson: string;
  /** Parsed entries (one per Task) once validation passes. */
  tasks: ItemsListTask[];
  errors: ImportError[];
  createdTaskIds: string[];
}

export type CloudEvent =
  | { type: 'STORAGE_VERIFIED'; storageMethodId: string } // includes 'public'
  | { type: 'RESET_STORAGE' }
  | { type: 'PREPARE_LIST' }
  | { type: 'SET_ITEMS_LIST'; json: string }
  | { type: 'IMPORT_DATA' }
  | { type: 'VALIDATE_OK'; tasks: ItemsListTask[] }
  | { type: 'VALIDATE_FAIL'; errors: ImportError[] }
  | { type: 'TASKS_CREATED'; taskIds: string[] }
  | { type: 'IMPORT_FAIL'; errors?: ImportError[] }
  | { type: 'RETRY' };

export interface CloudMachine {
  state: CloudState;
  context: CloudContext;
}

export const initialCloudContext: CloudContext = {
  storageMethodId: null,
  itemsListJson: '',
  tasks: [],
  errors: [],
  createdTaskIds: [],
};

export const initialCloudMachine: CloudMachine = {
  state: 'StorageNotReady',
  context: initialCloudContext,
};
