// resources/js/stores/franchiseStore.js
import api from '@/api/axios';
import { defineStore } from 'pinia';
import {
  extractErrorMessage,
  extractResponseData,
  removeItemFromArray,
  showToast,
  updateItemInArray
} from '../composables/useStoreHelpers';
import { createCacheManager } from '../utils/cacheManager';

// 🔥 CACHE CONFIGURATION
const cacheManager = createCacheManager('franchisees', 10 * 60 * 1000) // 10 minutes

export const useFranchiseeStore = defineStore('franchisees', {
  state: () => ({
    franchisees: [],
    total: 0,
    loading: false,
    saving: false,
    deleting: false,
    permanentDeleting: false,
    generatingLink: false,
    error: null,
    selectedFranchisee: null,
  }),

  actions: {
    async fetchFranchiseesLazy({ page = 1, rows = 10, sortField = '', sortOrder = '', search = '' }) {
      const cacheKey = cacheManager.generateKey({ page, rows, sortField, sortOrder, search })
      
      // ✅ Check cache first
      const cachedData = cacheManager.load(cacheKey)
      if (cachedData) {
        console.log('📦 Using cached data for franchisees')
        this.franchisees = cachedData.franchisees || []
        this.total = cachedData.total || 0
        return {
          success: true,
          fromCache: true,
          data: {
            data: this.franchisees,
            total: this.total
          }
        }
      }

      this.loading = true
      this.error = null
      
      try {
        console.log('🔄 Fetching fresh franchisees data from API')
        const response = await api.get('admin/franchisees/all', {
          params: {
            page,
            per_page: rows,
            sort_by: sortField,
            sort_order: sortOrder === 1 ? 'asc' : 'desc',
            search,
          },
        })
        
        // Handle different response structures
        if (response.data.data && Array.isArray(response.data.data.data)) {
          // Laravel pagination structure
          this.franchisees = response.data.data.data
          this.total = response.data.data.total
        } else if (response.data.data && Array.isArray(response.data.data)) {
          // Direct data array
          this.franchisees = response.data.data
          this.total = response.data.total || response.data.data.length
        } else if (Array.isArray(response.data)) {
          // Direct array response
          this.franchisees = response.data
          this.total = response.data.length
        } else {
          // Fallback
          console.warn('Unexpected response structure:', response.data)
          this.franchisees = []
          this.total = 0
        }

        // Save to cache
        cacheManager.save(cacheKey, {
          franchisees: this.franchisees,
          total: this.total
        })
        cacheManager.clearExpired()
        
        return response.data
      } catch (error) {
        this.error = extractErrorMessage(error)
        console.error('Error fetching franchisees:', error)
        this.franchisees = []
        this.total = 0
        showToast('error', 'Error', this.error)
        throw error
      } finally {
        this.loading = false
      }
    },

    async createFranchisee(data) {
      this.saving = true
      this.error = null
      
      try {
        const response = await api.post('admin/franchisees/add', data)
        const newFranchisee = extractResponseData(response)
        
        // Add to local array if we have data loaded
        if (this.franchisees.length > 0) {
          this.franchisees.unshift(newFranchisee)
          this.total++
        }
        
        cacheManager.clearAll()
        showToast('success', 'Success', 'Franchisee created successfully')
        
        return response.data
      } catch (error) {
        console.error('Create franchisee error:', error)
        this.error = extractErrorMessage(error)
        showToast('error', 'Error', this.error)
        throw error
      } finally {
        this.saving = false
      }
    },

    async updateFranchisee(id, data) {
      this.saving = true
      this.error = null
      
      try {
        const response = await api.put(`admin/franchisees/${id}`, data)
        const updatedFranchisee = extractResponseData(response)
        
        // Update in local array
        this.franchisees = updateItemInArray(this.franchisees, id, updatedFranchisee)
        
        // Update selected franchisee if it's the same
        if (this.selectedFranchisee?.id === id) {
          this.selectedFranchisee = updatedFranchisee
        }
        
        cacheManager.clearAll()
        showToast('success', 'Success', 'Franchisee updated successfully')
        
        return response.data
      } catch (error) {
        console.error('Update franchisee error:', error)
        this.error = extractErrorMessage(error)
        showToast('error', 'Error', this.error)
        throw error
      } finally {
        this.saving = false
      }
    },

    async deleteFranchisee(id) {
      this.deleting = true
      this.error = null
      
      try {
        await api.delete(`admin/franchisees/${id}`)
        
        // Remove from local array
        this.franchisees = removeItemFromArray(this.franchisees, id)
        this.total--
        
        // Clear selected if it's the deleted one
        if (this.selectedFranchisee?.id === id) {
          this.selectedFranchisee = null
        }
        
        cacheManager.clearAll()
        showToast('success', 'Deleted', 'Franchisee deleted successfully')
        
        return true
      } catch (error) {
        this.error = extractErrorMessage(error)
        showToast('error', 'Error', this.error)
        throw error
      } finally {
        this.deleting = false
      }
    },

    async permanentDeleteFranchisee(id) {
      this.permanentDeleting = true
      this.error = null

      try {
        await api.delete(`admin/franchisees/permanent-delete/${id}`)

        // Remove from local array
        this.franchisees = removeItemFromArray(this.franchisees, id)
        this.total--

        // Clear selected if it's the deleted one
        if (this.selectedFranchisee?.id === id) {
          this.selectedFranchisee = null
        }

        cacheManager.clearAll()
        showToast('success', 'Permanently Deleted', 'Franchisee has been permanently deleted')

        return true
      } catch (error) {
        this.error = extractErrorMessage(error)
        showToast('error', 'Error', this.error)
        throw error
      } finally {
        this.permanentDeleting = false
      }
    },

    async getFranchisee(id) {
      try {
        const response = await api.get(`admin/franchisees/${id}`)
        this.selectedFranchisee = extractResponseData(response)
        return response.data
      } catch (error) {
        this.error = extractErrorMessage(error)
        showToast('error', 'Error', this.error)
        throw error
      }
    },

    async generateLoginLink(franchiseeId) {
      this.generatingLink = true
      this.error = null

      try {
        const response = await api.post(`admin/impersonate/start/${franchiseeId}`)
        if (response.status && response.data?.data?.redirect_url) {
          return {
            success: true,
            url: response.data.data.redirect_url,
            franchisee: this.franchisees.find(f => f.id === franchiseeId)
          }
        } else {
          throw new Error('No URL in response')
        }
      } catch (error) {
        this.error = extractErrorMessage(error)
        console.error('Error generating login link:', error)
        return {
          success: false,
          error: this.error
        }
      } finally {
        this.generatingLink = false
      }
    },

    // ✅ NEW: Clear all cache to force fresh API calls
    clearCache() {
      console.log('🗑️ Clearing all franchisees cache')
      cacheManager.clearAll()
    },

    // ✅ NEW: Clear specific page cache
    clearCacheForCurrentPage(params = {}) {
      const cacheKey = cacheManager.generateKey(params)
      console.log('🗑️ Clearing cache for key:', cacheKey)
      cacheManager.clearByKey(cacheKey)
    },

    // Helper methods
    clearError() {
      this.error = null
    },

    setSelectedFranchisee(franchisee) {
      this.selectedFranchisee = franchisee
    },

    clearSelectedFranchisee() {
      this.selectedFranchisee = null
    }
  },

  getters: {
    isLoading: (state) => state.loading || state.saving || state.deleting || state.permanentDeleting,
    hasError: (state) => !!state.error,
    franchiseesCount: (state) => state.franchisees.length,
  },
})
