import { defineStore } from 'pinia'
import { LocalStorage } from 'quasar'
import type { IncomeData } from '../types/types'

const STORAGE_KEY = 'income:v1'

const DEFAULT: IncomeData = {
  employType: null,
  attachments: {
    salaryCertificate: { comments: '', attachments: [] },
    accountingDocuments: { comments: '', attachments: [] },
    avsCertificate: { comments: '', attachments: [] },
    lppCertificate: { comments: '', attachments: [] },
    unemploymentCertificate: { comments: '', attachments: [] }
  }
}

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

export const useIncomeStore = defineStore('incomestore', {
  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<IncomeData>) } as IncomeData }
      }
    } catch {
      // ignore and fall back to default
    }

    return { data: { ...DEFAULT } as IncomeData }
  },
  actions: {
    persist() {
      try {
        LocalStorage.set(STORAGE_KEY, this.data)
      } catch (err) {
        console.error('income.store: persist error', err)
      }
    },
    getIncome() {
      return this.data
    },
    setIncome(partial: Partial<IncomeData>) {
      this.data = { ...this.data, ...partial }
      this.persist()
    },
    replaceIncome(payload: IncomeData) {
      this.data = payload
      this.persist()
    },
    resetIncome() {
      this.data = { ...DEFAULT }
      this.persist()
    }
  }
})
