// ── Entity registry ──────────────────────────────────────────────────────────
// Maps Supabase table names → their offline store configuration.
// This is the single source of truth for which tables are offline-capable.

export interface OfflineEntityConfig {
  /** Supabase table name */
  table: string
  /** Dexie store name in db.ts */
  storeName: string
  /** Default cache TTL in milliseconds */
  ttlMs: number
  /** Whether writes to this table should be queued when offline */
  queueWrites: boolean
  /** Primary key column name in Supabase */
  primaryKey: string
  /**
   * Supabase select string passed to .select() when pulling.
   * Defaults to '*'. Use for tables that need joins.
   */
  pullSelect?: string
  /**
   * Whether pull sync may use updated_at >= lastFetchedAt.
   * Default: true.
   * Set to false for catalog/master or legacy tables without an updated_at
   * column — otherwise PostgREST returns 400 on the column filter.
   */
  incrementalSync?: boolean
}

const registry = new Map<string, OfflineEntityConfig>()

export function registerOfflineStore(config: OfflineEntityConfig): void {
  registry.set(config.table, config)
}

export function getOfflineConfig(table: string): OfflineEntityConfig | undefined {
  return registry.get(table)
}

export function getAllOfflineConfigs(): OfflineEntityConfig[] {
  return Array.from(registry.values())
}

export function isOfflineCapable(table: string): boolean {
  return registry.has(table)
}

// ── Registrations ─────────────────────────────────────────────────────────────

// ── Assessment ────────────────────────────────────────────────────────────────

registerOfflineStore({
  table:        'assessment_responses',
  storeName:    'assessmentResponses',
  ttlMs:        30 * 60 * 1000,  // 30 min
  queueWrites:  true,
  primaryKey:   'id',
})

registerOfflineStore({
  table:        'assessments',
  storeName:    'assessments',
  ttlMs:        60 * 60 * 1000,  // 1 hour
  queueWrites:  true,
  primaryKey:   'id',
})

registerOfflineStore({
  table:       'assessment_questions',
  storeName:   'assessmentQuestions',
  ttlMs:       24 * 60 * 60 * 1000, // 24 hours — catalog changes rarely
  queueWrites: false,                 // read-only catalog data
  primaryKey:  'id',
  pullSelect:  '*, main_category:assessment_main_categories(*), sub_category:assessment_sub_categories(*)',
})

// ── Planning ──────────────────────────────────────────────────────────────────

registerOfflineStore({
  table:        'assignments',
  storeName:    'assignments',
  ttlMs:        15 * 60 * 1000,  // 15 min
  queueWrites:  true,
  primaryKey:   'id',
})

registerOfflineStore({
  table:       'consultants',
  storeName:   'consultants',
  ttlMs:       60 * 60 * 1000,  // 1 hour
  queueWrites: false,             // admin-managed, not edited by field users
  primaryKey:  'id',
})

registerOfflineStore({
  table:           'appointment_types',
  storeName:       'appointmentTypes',
  ttlMs:           24 * 60 * 60 * 1000, // 24 hours
  queueWrites:     false,
  primaryKey:      'id',
  // Schema lacks updated_at — full fetch only.
  incrementalSync: false,
})

// ── Projects ──────────────────────────────────────────────────────────────────

registerOfflineStore({
  table:        'projects',
  storeName:    'projects',
  ttlMs:        60 * 60 * 1000,  // 1 hour
  queueWrites:  true,
  primaryKey:   'id',
})

registerOfflineStore({
  table:           'process_steps',
  storeName:       'processSteps',
  ttlMs:           30 * 60 * 1000,  // 30 min
  queueWrites:     true,
  primaryKey:      'id',
  // Schema lacks updated_at — full fetch only.
  incrementalSync: false,
})

registerOfflineStore({
  table:        'cycle_measurements',
  storeName:    'cycleMeasurements',
  ttlMs:        30 * 60 * 1000,
  queueWrites:  true,
  primaryKey:   'id',
})

registerOfflineStore({
  table:        'workshop_actions',
  storeName:    'workshopActions',
  ttlMs:        15 * 60 * 1000,  // 15 min — frequently updated
  queueWrites:  true,
  primaryKey:   'id',
})

registerOfflineStore({
  table:           'qaf_uploads',
  storeName:       'qafUploads',
  ttlMs:           60 * 60 * 1000,
  queueWrites:     false,            // file uploads go through separate flow
  primaryKey:      'id',
  // Schema has uploaded_at but no updated_at — full fetch only.
  incrementalSync: false,
})

// ── LSC ───────────────────────────────────────────────────────────────────────

registerOfflineStore({
  table:        'lsc_shifts',
  storeName:    'lscShifts',
  ttlMs:        30 * 60 * 1000,  // 30 min — same as cycle_measurements
  queueWrites:  true,
  primaryKey:   'id',
})

registerOfflineStore({
  table:        'lsc_shift_hours',
  storeName:    'lscShiftHours',
  ttlMs:        30 * 60 * 1000,  // 30 min
  queueWrites:  true,
  primaryKey:   'id',
})

// ── Account ───────────────────────────────────────────────────────────────────
// User profile is the consultant record for the logged-in user.
// The 'consultants' store (already registered above) is shared between planning
// and account — account-repo filters by auth user_id.
//
// Note: there used to be an offline registry entry for a 'profiles' table here.
// KADi has no `profiles` table — the profile data lives in `user_profiles` and
// is loaded directly through `lib/repositories/account-repo.ts` against Dexie's
// userProfiles store. The registry entry only caused fullSync() to issue
// `profiles?select=*` requests that 404'd in the browser console. Removed
// without replacement: no offline consumer depends on the sync-engine path.
