import type { GeoPoint, MapViewport } from '@/domain/poi'
import { defineStore } from 'pinia'

export const DEFAULT_GUANGMING_VIEWPORT: MapViewport = {
  longitude: 113.935,
  latitude: 22.748,
  scale: 11,
}

interface MapSessionState {
  categoryCode: string | null
  selectedPoiId: string | null
  viewport: MapViewport
}

function isFinitePoint(point: GeoPoint): boolean {
  return Number.isFinite(point.longitude) && Number.isFinite(point.latitude)
}

export const useMapStore = defineStore('map-session', {
  state: (): MapSessionState => ({
    categoryCode: null,
    selectedPoiId: null,
    viewport: { ...DEFAULT_GUANGMING_VIEWPORT },
  }),
  actions: {
    setCategory(categoryCode: string | null) {
      this.categoryCode = categoryCode
    },
    selectPoi(poiId: string | null) {
      this.selectedPoiId = poiId
    },
    updateViewport(viewport: MapViewport) {
      if (!isFinitePoint(viewport) || !Number.isFinite(viewport.scale) || viewport.scale <= 0)
        return

      this.viewport = { ...viewport }
    },
    resetViewport(viewport: MapViewport = DEFAULT_GUANGMING_VIEWPORT) {
      this.viewport = { ...viewport }
    },
    resetSession(viewport: MapViewport = DEFAULT_GUANGMING_VIEWPORT) {
      this.categoryCode = null
      this.selectedPoiId = null
      this.viewport = { ...viewport }
    },
  },
})
