// Crash-/refresh-safe draft persistence for workshop-erfassung form state.
//
// The client form saves observation and optimization values per-station.
// On network/server failure, the entered values were previously lost on reload.
// This store mirrors the entire form draft into localStorage, keyed by projectId,
// so it survives a page refresh. The draft is cleared after a successful server save.
//
// Pure and framework-agnostic — React components inject window.localStorage;
// tests inject an in-memory stand-in. Follows the pattern from
// lib/stopwatch/pending-measurements.ts.

export interface DraftStorage {
  getItem(key: string): string | null
  setItem(key: string, value: string): void
  removeItem(key: string): void
}

export interface ObservationDraft {
  observed_ct_sec: number | null
  machine_time_sec: number | null
  value_add_time_sec: number | null
  non_va_time_sec: number | null
  load_unload_time_sec: number | null
  waiting_time_sec: number | null
  output_per_shift: number | null
  scrap_count: number | null
  actual_oee: number | null
  comment: string | null
}

export interface OptimizationDraft {
  possible_ct_sec: number | null
  machine_time_sec: number | null
  value_add_time_sec: number | null
  non_va_time_sec: number | null
  load_unload_time_sec: number | null
  waiting_time_sec: number | null
  comment: string | null
}

export interface WorkshopDraft {
  projectId: string
  savedAt: string
  observations: Record<string, ObservationDraft>
  optimizations: Record<string, OptimizationDraft>
}

const KEY_PREFIX = 'kadi:workshop-draft:v1:'

function storageKey(projectId: string): string {
  return KEY_PREFIX + projectId
}

function resolveStorage(storage?: DraftStorage | null): DraftStorage | null {
  if (storage !== undefined) return storage
  if (typeof window === 'undefined') return null
  try {
    return window.localStorage as DraftStorage
  } catch {
    return null
  }
}

/** Load the stored draft for a project, or null if none exists. */
export function loadDraft(
  projectId: string,
  storage?: DraftStorage | null,
): WorkshopDraft | null {
  const store = resolveStorage(storage)
  if (!store) return null
  try {
    const raw = store.getItem(storageKey(projectId))
    if (!raw) return null
    const parsed = JSON.parse(raw) as unknown
    if (
      typeof parsed !== 'object' ||
      parsed === null ||
      (parsed as WorkshopDraft).projectId !== projectId
    ) {
      return null
    }
    return parsed as WorkshopDraft
  } catch {
    return null
  }
}

/** Persist the current draft for a project. */
export function saveDraft(
  draft: WorkshopDraft,
  storage?: DraftStorage | null,
): void {
  const store = resolveStorage(storage)
  if (!store) return
  try {
    store.setItem(storageKey(draft.projectId), JSON.stringify(draft))
  } catch {
    // Quota or serialization failure — silent.
  }
}

/** Remove the draft once the server has confirmed the save. */
export function clearDraft(
  projectId: string,
  storage?: DraftStorage | null,
): void {
  const store = resolveStorage(storage)
  if (!store) return
  try {
    store.removeItem(storageKey(projectId))
  } catch {
    // Ignore.
  }
}
