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

export const useMarketMailMappingStore = defineStore('marketMailMapping', {
  state: () => ({
    loading: false,
    saving: false,
    markets: [],
    mails: [],
    rows: []
  }),

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

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

    async saveMarketMails (marketId, mailIds) {
      this.saving = true
      try {
        await api.put(`/system/market-mail-mappings/${marketId}`, {
          mail_ids: Array.isArray(mailIds) ? mailIds : []
        })
      } finally {
        this.saving = false
      }
    }
  }
})

