// src/stores/OrderProductionUpdateStore.js
import { defineStore } from 'pinia'
import api from 'src/services/api'

let lastRequestId = 0

export const useOrderProductionUpdateStore = defineStore('orderproductionupdate', {
  state: () => ({
    orders: [],
    loading: false,
    error: null,

    filters: {
      search: '',
      CurrAccCode: '',
      OrderDate: ''
    }
  }),

  getters: {
    filteredOrders (state) {
      let result = state.orders

      if (state.filters.CurrAccCode) {
        result = result.filter(o => o.CurrAccCode === state.filters.CurrAccCode)
      }

      if (state.filters.OrderDate) {
        result = result.filter(o =>
          o.OrderDate?.startsWith(state.filters.OrderDate)
        )
      }

      return result
    },

    totalVisibleUSD () {
      return this.filteredOrders.reduce((sum, o) => {
        const value = Number(o.TotalAmountUSD || 0)
        return sum + (Number.isFinite(value) ? value : 0)
      }, 0)
    },

    totalPackedVisibleUSD () {
      return this.filteredOrders.reduce((sum, o) => {
        const value = Number(o.PackedUSD || 0)
        return sum + (Number.isFinite(value) ? value : 0)
      }, 0)
    },

    packedVisibleRatePct () {
      if (!this.totalVisibleUSD) return 0
      return (this.totalPackedVisibleUSD / this.totalVisibleUSD) * 100
    }
  },

  actions: {
    async fetchOrders () {

      // ==============================
      // 📌 REQUEST ID
      // ==============================
      const rid = ++lastRequestId

      // ==============================
      // 📌 SEARCH SNAPSHOT
      // ==============================
      const raw = this.filters.search ?? ''
      const trimmed = String(raw).trim()

      // ==============================
      // 📌 REQUEST LOG
      // ==============================
      console.groupCollapsed(
        `%c[orders-prod] FETCH rid=${rid}`,
        'color:#1976d2;font-weight:bold'
      )

      console.log('raw      =', JSON.stringify(raw), 'len=', String(raw).length)
      console.log('trimmed  =', JSON.stringify(trimmed), 'len=', trimmed.length)
      console.log('filters  =', JSON.parse(JSON.stringify(this.filters)))
      console.log('lastRID  =', lastRequestId)

      console.groupEnd()

      this.loading = true
      this.error = null

      try {

        // ==============================
        // 📌 PARAMS
        // ==============================
        const params = {}
        if (trimmed) params.search = trimmed

        // ==============================
        // 📌 API CALL
        // ==============================
        const res = await api.get('/orders/production-list', { params })

        // ==============================
        // 📌 STALE CHECK
        // ==============================
        if (rid !== lastRequestId) {
          console.warn(
            `[orders-prod] IGNORE stale response rid=${rid} last=${lastRequestId}`
          )
          return
        }

        // ==============================
        // 📌 DATA
        // ==============================
        const data = res?.data
        this.orders = Array.isArray(data) ? data : []

        // ==============================
        // 📌 RESPONSE LOG
        // ==============================
        console.groupCollapsed(
          `%c[orders-prod] RESPONSE rid=${rid} count=${this.orders.length}`,
          'color:#2e7d32;font-weight:bold'
        )

        console.log('status =', res?.status)

        console.log(
          'sample =',
          this.orders.slice(0, 5).map(o => ({
            id: o.OrderHeaderID,
            no: o.OrderNumber,
            code: o.CurrAccCode,
            name: o.CurrAccDescription
          }))
        )

        console.groupEnd()

      } catch (err) {

        if (rid !== lastRequestId) return

        console.error(
          '[orders-prod] FETCH FAILED',
          err?.response?.status,
          err?.response?.data || err
        )

        this.orders = []

        this.error =
          err?.response?.data ||
          err?.message ||
          'Sipariş listesi alınamadı'

      } finally {

        if (rid === lastRequestId) {
          this.loading = false
        }

      }
    }
  }
})
