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

export const usePricingMailMappingStore = defineStore('pricingMailMapping', {
  state: () => ({
    loading: false,
    saving: false,
    firstGroups: [],
    mails: [],
    rows: []
  }),

  actions: {
    async fetchLookups () {
      this.loading = true
      try {
        const res = await api.get('/system/pricing-mail-mappings/lookups')
        const payload = res?.data || {}
        this.firstGroups = Array.isArray(payload.first_groups) ? payload.first_groups : []
        this.mails = Array.isArray(payload.mails) ? payload.mails : []
      } finally {
        this.loading = false
      }
    },

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

    async saveGroupMails (urunIlkGrubu, mailIds) {
      this.saving = true
      try {
        await api.put(`/system/pricing-mail-mappings/${encodeURIComponent(String(urunIlkGrubu || '').trim())}`, {
          mail_ids: Array.isArray(mailIds) ? mailIds : []
        })
      } finally {
        this.saving = false
      }
    }
  }
})

