import { http } from 'msw'
import { jsonResponse, noContent } from '../helpers'
import type {
  AiRecognitionSettings,
  AiRecognitionTelemetry,
  GpsDeviceSettings,
  GpsDeviceTelemetry,
} from '../../../src/types'

// Stateful MSW handlers for AI Recognition + GPS Device Link settings.
// Seed mutates on PATCH so PING / RECONNECT / APPLY round-trips persist
// within a session. `resetAdminSettingsSeed()` is invoked per-test from
// tests/setup.ts so test isolation is preserved.

const DEFAULT_AI_SETTINGS: AiRecognitionSettings = {
  framesToRecognize: 4,
  minSecondsBetween: 2,
  minConfidence: 25,
}

const DEFAULT_AI_TELEMETRY: AiRecognitionTelemetry = {
  model: 'YOLOV8-X',
  checkpoint: 'CKPT-241',
  lastRunAt: '2026-05-18T11:43:09Z',
  frames: 14228,
  avgConfidence: 71.4,
}

const DEFAULT_GPS_SETTINGS: GpsDeviceSettings = {
  address: '192.168.1.100',
  port: 9001,
  protocol: 'NMEA',
}

const DEFAULT_GPS_TELEMETRY: GpsDeviceTelemetry = {
  socket: 'UDP/192.168.1.100:9001',
  connected: true,
  fix: '3D',
  satellites: 11,
  hdop: 0.82,
  lastPacketMs: 12,
}

let aiSettings: AiRecognitionSettings = { ...DEFAULT_AI_SETTINGS }
let aiTelemetry: AiRecognitionTelemetry = { ...DEFAULT_AI_TELEMETRY }
let gpsSettings: GpsDeviceSettings = { ...DEFAULT_GPS_SETTINGS }
let gpsTelemetry: GpsDeviceTelemetry = { ...DEFAULT_GPS_TELEMETRY }

export function resetAdminSettingsSeed() {
  aiSettings = { ...DEFAULT_AI_SETTINGS }
  aiTelemetry = { ...DEFAULT_AI_TELEMETRY }
  gpsSettings = { ...DEFAULT_GPS_SETTINGS }
  gpsTelemetry = { ...DEFAULT_GPS_TELEMETRY }
}

export const adminSettingsHandlers = [
  http.get('/api/admin/ai-settings', () =>
    jsonResponse({ settings: aiSettings, telemetry: aiTelemetry }),
  ),

  http.patch('/api/admin/ai-settings', async ({ request }) => {
    const body = (await request.json().catch(() => ({}))) as Partial<AiRecognitionSettings>
    aiSettings = { ...aiSettings, ...body }
    return jsonResponse({ settings: aiSettings, telemetry: aiTelemetry })
  }),

  http.get('/api/admin/gps-settings', () =>
    jsonResponse({ settings: gpsSettings, telemetry: gpsTelemetry }),
  ),

  http.patch('/api/admin/gps-settings', async ({ request }) => {
    const body = (await request.json().catch(() => ({}))) as Partial<GpsDeviceSettings>
    gpsSettings = { ...gpsSettings, ...body }
    gpsTelemetry = {
      ...gpsTelemetry,
      socket: `UDP/${gpsSettings.address}:${gpsSettings.port}`,
    }
    return jsonResponse({ settings: gpsSettings, telemetry: gpsTelemetry })
  }),

  http.post('/api/admin/gps-settings/ping', () => noContent()),

  http.post('/api/admin/gps-settings/reconnect', () => {
    gpsTelemetry = { ...gpsTelemetry, connected: true, lastPacketMs: 0 }
    return jsonResponse({ settings: gpsSettings, telemetry: gpsTelemetry })
  }),
]
