import { defineStore } from 'pinia'
import api from 'src/services/api'

export const useOrderPriceListUserPriceGroupStore = defineStore('orderPriceListUserPriceGroup', {
  state: () => ({
    loading: false,
    saving: false,
    rows: [],
    priceGroupOptions: []
  }),

  actions: {
    async fetchLookups () {
      const res = await api.get('/system/order-price-list-user-price-groups/lookups')
      this.priceGroupOptions = (res?.data?.price_groups || []).map((x) => ({
        label: x.label || x.value,
        value: x.value
      }))
    },

    async fetchRows () {
      this.loading = true
      try {
        const res = await api.get('/system/order-price-list-user-price-groups')
        this.rows = Array.isArray(res?.data) ? res.data : []
      } finally {
        this.loading = false
      }
    },

    async saveUserPriceGroups (userId, priceGroups) {
      this.saving = true
      try {
        await api.put(`/system/order-price-list-user-price-groups/${encodeURIComponent(String(userId))}`, {
          price_groups: Array.isArray(priceGroups) ? priceGroups : []
        })
      } finally {
        this.saving = false
      }
    }
  }
})
