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

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

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

function isUsableViewport(viewport: MapViewport): boolean {
  return isTrustworthyCoordinate(viewport.longitude, viewport.latitude)
    && Number.isFinite(viewport.scale)
    && viewport.scale > 0
}

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

      this.viewport = { ...viewport }
    },
    resetViewport(viewport: MapViewport = DEFAULT_GUANGMING_VIEWPORT) {
      this.viewport = isUsableViewport(viewport)
        ? { ...viewport }
        : { ...DEFAULT_GUANGMING_VIEWPORT }
    },
    showPlannedRoute() {
      this.plannedRouteVisible = true
    },
    hidePlannedRoute() {
      this.plannedRouteVisible = false
    },
    resetSession(viewport: MapViewport = DEFAULT_GUANGMING_VIEWPORT) {
      this.categoryCode = null
      this.selectedPoiId = null
      this.viewport = isUsableViewport(viewport)
        ? { ...viewport }
        : { ...DEFAULT_GUANGMING_VIEWPORT }
      this.plannedRouteVisible = false
    },
  },
})
