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

export const useOrderBulkCloseStore = defineStore('orderBulkClose', {
  state: () => ({
    orders: [],
    selectedOrderNumbers: [],
    search: '',
    loading: false,
    closing: false,
    error: null
  }),

  getters: {
    selectedCount (state) {
      return state.selectedOrderNumbers.length
    },

    totalCount (state) {
      return state.orders.length
    }
  },

  actions: {
    isSelected (orderNumber) {
      return this.selectedOrderNumbers.includes(orderNumber)
    },

    setSelected (orderNumber, selected) {
      if (!orderNumber) return

      if (selected) {
        if (!this.selectedOrderNumbers.includes(orderNumber)) {
          this.selectedOrderNumbers.push(orderNumber)
        }
        return
      }

      this.selectedOrderNumbers = this.selectedOrderNumbers.filter(
        (n) => n !== orderNumber
      )
    },

    toggleSelectMany (orderNumbers, selected) {
      const clean = Array.from(
        new Set((orderNumbers || []).filter(Boolean))
      )

      if (selected) {
        const current = new Set(this.selectedOrderNumbers)
        clean.forEach((n) => current.add(n))
        this.selectedOrderNumbers = Array.from(current)
        return
      }

      const block = new Set(clean)
      this.selectedOrderNumbers = this.selectedOrderNumbers.filter(
        (n) => !block.has(n)
      )
    },

    clearSelection () {
      this.selectedOrderNumbers = []
    },

    async fetchOrders () {
      this.loading = true
      this.error = null

      try {
        const search = String(this.search || '').trim()
        const params = {}
        if (search) params.search = search

        const res = await api.get('/orders/close-ready', { params })
        this.orders = Array.isArray(res?.data) ? res.data : []

        // new list disinda kalan secimleri temizle
        const available = new Set(this.orders.map((o) => o.OrderNumber))
        this.selectedOrderNumbers = this.selectedOrderNumbers.filter(
          (n) => available.has(n)
        )
      } catch (err) {
        this.orders = []
        this.error =
          err?.response?.data ||
          err?.message ||
          'Siparişler alınamadı'
      } finally {
        this.loading = false
      }
    },

    async closeSelectedOrders () {
      if (!this.selectedOrderNumbers.length) {
        return { affected: 0 }
      }

      this.closing = true
      this.error = null

      try {
        const payload = {
          order_numbers: this.selectedOrderNumbers
        }

        const res = await api.post('/orders/bulk-close', payload)
        const affected = Number(res?.data?.affected || 0)

        // local optimizasyon: secilenleri listeden dus
        const selected = new Set(this.selectedOrderNumbers)
        this.orders = this.orders.filter((o) => !selected.has(o.OrderNumber))
        this.selectedOrderNumbers = []

        return { affected }
      } catch (err) {
        this.error =
          err?.response?.data ||
          err?.message ||
          'Toplu kapatma başarısız'
        throw err
      } finally {
        this.closing = false
      }
    }
  }
})
