// src/stores/counts.ts

import { ref } from 'vue'
import { defineStore } from 'pinia'
import { adminService } from '../services/adminService'

export const useCountsStore = defineStore('counts', () => {
  // --- STATE ---
  // All counts are now stored here, centrally.
  const today = ref(0)
  const tomorrow = ref(0)
  const waiting = ref(0)
  const pending = ref(0)
  const automatic = ref(0)
  const upcomingService = ref(0)
  const todayService = ref(0)
  const transaction = ref(0)

  // --- ACTIONS ---
  // A single action to fetch ALL counts from our new, efficient endpoint.
  async function fetchSidebarCounts() {
    try {
      const response = await adminService.stats.sidebarCounts();

      if (response.data && response.data.ok) {
        const counts = response.data.counts;
        today.value = counts.today;
        tomorrow.value = counts.tomorrow;
        waiting.value = counts.waiting;
        pending.value = counts.pending;
        automatic.value = counts.automatic;
        upcomingService.value = counts.upcoming_service;
        todayService.value = counts.today_service || 0;
        transaction.value = counts.transaction || 0;
      }
    } catch {
      // No error param, as requested
      // Optionally reset counts on error
      console.error("Failed to fetch sidebar counts.");
    }
  }

  // --- RETURN ---
  // Expose the state and the action to the rest of the app.
  return {
    today,
    tomorrow,
    waiting,
    pending,
    automatic,
    upcomingService,
    todayService,
    transaction,
    fetchSidebarCounts,
  }
})
