import { defineStore } from 'pinia'
import { LocalStorage } from 'quasar'

export type CommuteMethod = 'CAR' | 'BUS' | 'BIKE' | 'WALK'

export interface ProfessionalExpensesData {
  expensesChanged: boolean
  workplaceDescription: string
  commuteMethod: CommuteMethod | null
  commuteKm: number | null
  lunchAtHome: boolean
  eatsOut: boolean
  hasCanteenOrVouchers: boolean
}

const STORAGE_KEY = 'professionalExpenses:v1'

const DEFAULT: ProfessionalExpensesData = {
  expensesChanged: false,
  workplaceDescription: '',
  commuteMethod: null,
  commuteKm: null,
  lunchAtHome: false,
  eatsOut: false,
  hasCanteenOrVouchers: false
}

function isRecord(v: unknown): v is Record<string, unknown> {
  return !!v && typeof v === 'object' && !Array.isArray(v)
}

export const useProfessionalExpensesStore = defineStore('professionalexpensesstore', {
  state: () => {
    try {
      let saved: unknown = LocalStorage.getItem(STORAGE_KEY)
      if (typeof saved === 'string') {
        try {
          saved = JSON.parse(saved)
        } catch {
          saved = null
        }
      }
      if (isRecord(saved)) {
        const merged = { ...DEFAULT, ...(saved as Partial<ProfessionalExpensesData>) } as ProfessionalExpensesData
        return {
          data: {
            ...merged,
            hasCanteenOrVouchers: merged.hasCanteenOrVouchers === true
          }
        }
      }
    } catch {
      // ignore and fall back to default
    }
    return { data: { ...DEFAULT } as ProfessionalExpensesData }
  },
  actions: {
    persist() {
      try {
        LocalStorage.set(STORAGE_KEY, this.data)
      } catch (err) {
        console.error('professionalExpenses.store: persist error', err)
      }
    },
    getProfessionalExpenses() {
      return this.data
    },
    setProfessionalExpenses(partial: Partial<ProfessionalExpensesData>) {
      this.data = { ...this.data, ...partial }
      this.persist()
    },
    replaceProfessionalExpenses(payload: ProfessionalExpensesData) {
      this.data = payload
      this.persist()
    },
    resetProfessionalExpenses() {
      this.data = { ...DEFAULT }
      this.persist()
    }
  }
})
