import { defineStore } from 'pinia'
import { store } from '/@/store'
import { Storage } from '@/utils/storage'
import { FARM_ID_KEY } from '@/enums/cacheEnum'

export interface Farm {
    id: string
    farmName: string
    farmType: string
    farmTypeText: string
}
interface FarmState {
    info: Nullable<Farm>
}
export const useFarmStore = defineStore({
    id: 'farm',
    state: (): FarmState => ({
        info: null,
    }),
    getters: {
        getFarm(): Nullable<Farm> {
            if (this.info) {
                return this.info
            }
            const storedInfo = Storage.get(FARM_ID_KEY)
            if (storedInfo) {
                const parsedInfo = JSON.parse(storedInfo) as Farm
                this.info = parsedInfo
                return parsedInfo
            }

            return null
        },
    },
    actions: {
        setFarmInfo(info: Farm) {
            console.log('setFarmInfo', info)
            this.info = info
            if (!info) {
                Storage.remove(FARM_ID_KEY)
            } else {
                Storage.set(FARM_ID_KEY, info ? JSON.stringify(info) : null)
            }
        },
    },
})

// Need to be used outside the setup
export function useFarmStoreWithOut() {
    return useFarmStore(store)
}
