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

function toText (value) {
  return String(value ?? '').trim()
}

function toNumber (value) {
  const n = Number(value)
  return Number.isFinite(n) ? Number(n.toFixed(2)) : 0
}

function mapRow (raw, index) {
  return {
    id: index + 1,
    productCode: toText(raw?.ProductCode),
    stockQty: toNumber(raw?.StockQty),
    stockEntryDate: toText(raw?.StockEntryDate),
    lastPricingDate: toText(raw?.LastPricingDate),
    askiliYan: toText(raw?.AskiliYan),
    kategori: toText(raw?.Kategori),
    urunIlkGrubu: toText(raw?.UrunIlkGrubu),
    urunAnaGrubu: toText(raw?.UrunAnaGrubu),
    urunAltGrubu: toText(raw?.UrunAltGrubu),
    icerik: toText(raw?.Icerik),
    karisim: toText(raw?.Karisim),
    marka: toText(raw?.Marka),
    brandGroupSelection: toText(raw?.BrandGroupSec),
    costPrice: toNumber(raw?.CostPrice),
    expenseForBasePrice: 0,
    basePriceUsd: 0,
    basePriceTry: 0,
    usd1: 0,
    usd2: 0,
    usd3: 0,
    usd4: 0,
    usd5: 0,
    usd6: 0,
    eur1: 0,
    eur2: 0,
    eur3: 0,
    eur4: 0,
    eur5: 0,
    eur6: 0,
    try1: 0,
    try2: 0,
    try3: 0,
    try4: 0,
    try5: 0,
    try6: 0
  }
}

export const useProductPricingStore = defineStore('product-pricing-store', {
  state: () => ({
    rows: [],
    loading: false,
    error: ''
  }),

  actions: {
    async fetchRows () {
      this.loading = true
      this.error = ''
      try {
        const res = await api.get('/pricing/products')
        const data = Array.isArray(res?.data) ? res.data : []
        this.rows = data.map((x, i) => mapRow(x, i))
      } catch (err) {
        this.rows = []
        const msg = err?.response?.data || err?.message || 'Urun fiyatlandirma listesi alinamadi'
        this.error = toText(msg)
      } finally {
        this.loading = false
      }
    },

    updateCell (row, field, val) {
      if (!row || !field) return
      row[field] = toNumber(String(val ?? '').replace(',', '.'))
    },

    updateBrandGroupSelection (row, val) {
      if (!row) return
      row.brandGroupSelection = toText(val)
    }
  }
})
