import { mockBeacons } from '../mock/mockBeacons'
import type { Beacon } from '../model/types'

const BEACONS_STORAGE_KEY = 'fleet-ble-monitor.beacons'

function cloneBeacon(beacon: Beacon): Beacon {
  return { ...beacon }
}

export function readBeacons(): Beacon[] {
  if (typeof window === 'undefined') {
    return mockBeacons.map(cloneBeacon)
  }

  const storedBeacons = window.localStorage.getItem(BEACONS_STORAGE_KEY)

  if (!storedBeacons) {
    const initialBeacons = mockBeacons.map(cloneBeacon)
    window.localStorage.setItem(BEACONS_STORAGE_KEY, JSON.stringify(initialBeacons))

    return initialBeacons
  }

  try {
    return (JSON.parse(storedBeacons) as Beacon[]).map(cloneBeacon)
  } catch {
    const initialBeacons = mockBeacons.map(cloneBeacon)
    window.localStorage.setItem(BEACONS_STORAGE_KEY, JSON.stringify(initialBeacons))

    return initialBeacons
  }
}

export function writeBeacons(beacons: Beacon[]) {
  if (typeof window === 'undefined') return

  window.localStorage.setItem(BEACONS_STORAGE_KEY, JSON.stringify(beacons))
  window.dispatchEvent(new Event('beacons:change'))
}

export const beaconsService = {
  async getBeacons(): Promise<Beacon[]> {
    return readBeacons().map(cloneBeacon)
  },

  async getFreeBeacons(): Promise<Beacon[]> {
    return readBeacons()
      .filter((beacon) => beacon.status === 'FREE')
      .map(cloneBeacon)
  },

  async getBeaconById(id: number | string): Promise<Beacon | null> {
    const numericId = Number(id)
    const beacon = readBeacons().find((item) => item.id === numericId)

    return beacon ? cloneBeacon(beacon) : null
  },
}
