// Data-import DOMAIN — Sample-Path reducer (pure). Source: data-import-spec.md §6 (V1/V2).

import { validateBucketRelativePath } from '../bucketPath';
import { initialSamplePathMachine, type SamplePathEvent, type SamplePathMachine } from './states';

export function samplePathReducer(m: SamplePathMachine, e: SamplePathEvent): SamplePathMachine {
  switch (e.type) {
    case 'PASTE_PATH': {
      // V1 — reject a non-bucket-relative path up front, before any network round-trip.
      const v1 = validateBucketRelativePath(e.path);
      if (v1) return { state: 'VerifyFailed', context: { path: e.path, preview: null, error: v1 } };
      return { state: 'Verifying', context: { path: e.path, preview: null, error: null } };
    }

    case 'VERIFY_OK':
      if (m.state !== 'Verifying') return m;
      return { state: 'Verified', context: { ...m.context, preview: e.preview, error: null } };

    case 'VERIFY_FAIL':
      if (m.state !== 'Verifying') return m;
      return { state: 'VerifyFailed', context: { ...m.context, preview: null, error: e.error } };

    case 'RESET':
      return initialSamplePathMachine;

    default:
      return m;
  }
}
