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

export interface SideIncomeData {
  hasSideIncome: boolean,
  sideIncomeDocuments: {
    comments: string,
    attachments: []
  }

}

const STORAGE_KEY = 'sideIncome:v1'

const DEFAULT: SideIncomeData = {
  hasSideIncome: false,
  sideIncomeDocuments:  { comments: '', attachments: [] }
}

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

export const useSideIncomeStore = defineStore('sideincomestore', {
  state: () => {
    try {
      let saved: unknown = LocalStorage.getItem(STORAGE_KEY)
      if (typeof saved === 'string') {
        try {
          saved = JSON.parse(saved)
        } catch {
          saved = null
        }
      }
      if (isRecord(saved)) {
        return { data: { ...DEFAULT, ...(saved as Partial<SideIncomeData>) } as SideIncomeData }
      }
    } catch {
      // ignore and fall back to default
    }
    return { data: { ...DEFAULT } as SideIncomeData }
  },
  actions: {
    persist() {
      try {
        LocalStorage.set(STORAGE_KEY, this.data)
      } catch (err) {
        console.error('sideIncome.store: persist error', err)
      }
    },
    getSideIncome() {
      return this.data
    },
    setSideIncome(partial: Partial<SideIncomeData>) {
      this.data = { ...this.data, ...partial }
      this.persist()
    },
    replaceSideIncome(payload: SideIncomeData) {
      this.data = payload
      this.persist()
    },
    resetSideIncome() {
      this.data = { ...DEFAULT }
      this.persist()
    }
  }
})
