/**
 * Import Session Types
 *
 * Types for managing product import session persistence,
 * including autosave and named session management.
 */

import type { RowData, ValidationError, UpcValidationStatus } from '@/components/product-import/steps/ValidationStep/store/types';
import type { ProductImageSortable } from '@/components/product-import/steps/ImageUploadStep/types';
import type { GlobalSelections } from '@/components/product-import/steps/MatchColumnsStep/types';

// =============================================================================
// Session Data Types
// =============================================================================

/**
 * Serialized validation state for database storage.
 * Maps are converted to plain objects for JSONB storage.
 */
export interface SerializedValidationState {
  /** Errors by row index, then by field key */
  errors: Record<number, Record<string, ValidationError[]>>;
  /** UPC validation status by row index */
  upcStatus: Record<number, UpcValidationStatus>;
  /** Generated item numbers by row index */
  generatedItemNumbers: Record<number, string>;
}

/**
 * Session data payload for API requests (create/update)
 */
export interface ImportSessionData {
  current_step: 'validation' | 'imageUpload';
  data: RowData[];
  product_images?: ProductImageSortable[];
  global_selections?: GlobalSelections;
  validation_state?: SerializedValidationState;
}

/**
 * Full session record from the database
 */
export interface ImportSession {
  id: number;
  user_id: number;
  name: string | null;
  current_step: 'validation' | 'imageUpload';
  data: RowData[];
  product_images: ProductImageSortable[] | null;
  global_selections: GlobalSelections | null;
  validation_state: SerializedValidationState | null;
  created_at: string;
  updated_at: string;
}

/**
 * Session list item (lighter version without full data)
 */
export interface ImportSessionListItem {
  id: number;
  user_id: number;
  name: string | null;
  current_step: 'validation' | 'imageUpload';
  row_count: number;
  global_selections: GlobalSelections | null;
  created_at: string;
  updated_at: string;
}

// =============================================================================
// Context Types
// =============================================================================

/**
 * Import session context state and actions
 */
export interface ImportSessionContextValue {
  /** Current session ID (null = new/unnamed session) */
  sessionId: number | null;
  /** Session name (null = unnamed autosave) */
  sessionName: string | null;
  /** Whether there are unsaved changes */
  isDirty: boolean;
  /** Timestamp of last successful save */
  lastSaved: Date | null;
  /** Whether a save operation is in progress */
  isSaving: boolean;
  /** Current step for session tracking */
  currentStep: 'validation' | 'imageUpload';

  /** Set the current step */
  setCurrentStep: (step: 'validation' | 'imageUpload') => void;
  /** Mark session as dirty (has unsaved changes) */
  markDirty: () => void;
  /** Save current state as a named session */
  saveAsNamed: (name: string) => Promise<ImportSession>;
  /** Update existing named session or create autosave */
  save: () => Promise<void>;
  /** Force immediate save (ignoring debounce), used before closing */
  forceSave: () => Promise<void>;
  /** Load a session by ID */
  loadSession: (session: ImportSession) => void;
  /** Clear current session state */
  clearSession: () => void;
  /** Delete session from server (called on submit) */
  deleteSession: () => Promise<void>;
  /** Set the data getter function for autosave */
  setDataGetter: (getter: () => ImportSessionData) => void;
  /** Get a suggested session name based on data (Company - Line) */
  getSuggestedSessionName: () => string | null;
  /** Store global selections for inclusion in autosave data */
  setGlobalSelections: (selections: GlobalSelections | undefined) => void;
  /** Get stored global selections */
  getGlobalSelections: () => GlobalSelections | undefined;
}

// =============================================================================
// Hook Types
// =============================================================================

export interface UseImportAutosaveOptions {
  /** Whether autosave is enabled */
  enabled: boolean;
  /** Debounce delay in milliseconds (default: 10000) */
  debounceMs?: number;
}

// =============================================================================
// API Response Types
// =============================================================================

export interface ImportSessionCreateRequest {
  user_id: number;
  name: string;
  current_step: 'validation' | 'imageUpload';
  data: RowData[];
  product_images?: ProductImageSortable[];
  global_selections?: GlobalSelections;
  validation_state?: SerializedValidationState;
}

export interface ImportSessionUpdateRequest {
  name?: string;
  current_step: 'validation' | 'imageUpload';
  data: RowData[];
  product_images?: ProductImageSortable[];
  global_selections?: GlobalSelections;
  validation_state?: SerializedValidationState;
}

export interface ImportSessionAutosaveRequest {
  user_id: number;
  current_step: 'validation' | 'imageUpload';
  data: RowData[];
  product_images?: ProductImageSortable[];
  global_selections?: GlobalSelections;
  validation_state?: SerializedValidationState;
}
