// ── Offline / Sync types ────────────────────────────────────────────────────
// Shared across all modules. Keep this file pure — no Dexie imports here.

export type SyncStatus = 'synced' | 'pending' | 'error' | 'conflict'
/** Alias used in local store entity types */
export type LocalSyncStatus = SyncStatus

export type OperationType = 'insert' | 'update' | 'delete' | 'upsert'

/** A single queued write waiting to be flushed to Supabase. */
export interface SyncQueueEntry {
  /** Auto-incremented by Dexie (aliased as autoId in the queue API) */
  id?: number
  /** Supabase table name, e.g. 'assessment_responses' */
  table: string
  /** insert | update | delete | upsert */
  operation: OperationType
  /** The full row payload (for insert/update/upsert) */
  payload?: Record<string, unknown>
  /** Primary key value for update/delete */
  recordId?: string
  /** Column to match on for upsert conflict resolution */
  conflictTarget?: string
  /** ISO timestamp when queued */
  createdAt: string
  /** Total execution attempts made */
  attempts: number
  /** Number of retry cycles (incremented by retryFailed()) */
  retryCount: number
  /** If true, exceeded MAX_RETRY_COUNT — will never auto-retry again */
  permanentlyFailed: boolean
  /** ISO timestamp of last sync attempt */
  lastAttemptAt?: string
  /** Error message from last failed attempt */
  lastError?: string
  /** Current sync status */
  status: SyncStatus
}

/** Result returned by startSync() and fullSync() */
export interface SyncResult {
  /** Write operations successfully pushed to Supabase */
  pushed: number
  /** Rows pulled from Supabase into local cache */
  pulled: number
  /** Write operations that failed after all retries */
  failed: number
  /** Writes where server data differed (LWW applied) */
  conflicts: number
}

/** Stored record of a resolved or unresolved sync conflict */
export interface SyncConflict {
  id?: number
  table: string
  recordId: string
  localVersion: Record<string, unknown>
  serverVersion: Record<string, unknown>
  /** Which version was kept */
  resolvedWith: 'local' | 'server' | 'unresolved'
  occurredAt: string
}

/** Metadata stored alongside each cached entity collection. */
export interface CacheMetadata {
  /** Unique key, e.g. 'assessment_responses:assess_123' */
  key: string
  /** When the cache was last populated from Supabase */
  lastFetchedAt: string
  /** How old (ms) the cache is allowed to be before a re-fetch is preferred */
  ttlMs: number
}

/** Connection state tracked by useOnlineStatus hook. */
export interface ConnectionState {
  isOnline: boolean
  /** When online status was last confirmed */
  lastOnlineAt: string | null
  /** When we went offline */
  lastOfflineAt: string | null
}
