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

export type UserLocationStatus = 'idle' | 'locating' | 'ready' | 'denied' | 'unavailable' | 'error'

export interface UserLocationSnapshot extends GeoPoint {
  accuracy: number | null
  capturedAt: string
  coordinateSystem: 'GCJ02'
}

interface UserLocationState {
  status: UserLocationStatus
  snapshot: UserLocationSnapshot | null
  errorMessage: string
}

export const useLocationStore = defineStore('user-location-session', {
  state: (): UserLocationState => ({
    status: 'idle',
    snapshot: null,
    errorMessage: '',
  }),
  actions: {
    startLocating() {
      this.status = 'locating'
      this.errorMessage = ''
    },
    updateLocation(longitude: number, latitude: number, accuracy?: number | null) {
      if (!isTrustworthyCoordinate(longitude, latitude))
        return false

      this.snapshot = {
        longitude,
        latitude,
        accuracy: Number.isFinite(accuracy) && Number(accuracy) >= 0 ? Number(accuracy) : null,
        capturedAt: new Date().toISOString(),
        coordinateSystem: 'GCJ02',
      }
      this.status = 'ready'
      this.errorMessage = ''
      return true
    },
    failLocation(status: Exclude<UserLocationStatus, 'idle' | 'locating' | 'ready'>, message: string) {
      this.status = status
      this.errorMessage = message
    },
  },
})
