import { defineStore } from 'pinia'
import axios from 'axios'
import { useOPFS } from '../composables/useOPFS'

const opfs = useOPFS()
const CACHE_KEY_STORES = 'cached_stores.json'

export const useStoreStore = defineStore('store', {
  state: () => ({
    stores: [],
    currentStore: null,
    storeProducts: [],
    loading: false,
    error: null
  }),
  actions: {
    async fetchStores() {
      this.loading = true
      this.error = null
      
      // Load from cache first
      try {
        const cachedStores = await opfs.loadJSON(CACHE_KEY_STORES)
        if (cachedStores && Array.isArray(cachedStores)) {
          this.stores = cachedStores
        }
      } catch (e) {
        console.warn('Failed to load stores from cache:', e)
      }

      try {
        const response = await axios.get('/api/stores')
        this.stores = response.data || []
        
        // Save to cache
        await opfs.saveJSON(CACHE_KEY_STORES, this.stores)
      } catch (error) {
        console.error('Failed to fetch stores:', error)
        this.error = error.message
      } finally {
        this.loading = false
      }
    },

    async fetchStoreByHash(hash) {
      this.loading = true
      this.error = null
      try {
        const response = await axios.get(`/api/stores/${hash}`)
        if (response.data && response.data.success) {
          this.currentStore = response.data.store
        }
      } catch (error) {
        console.error('Failed to fetch store:', error)
        this.error = error.message
      } finally {
        this.loading = false
      }
    },

    async createStore(data) {
      this.loading = true
      this.error = null
      try {
        const response = await axios.post('/api/stores', data)
        if (response.data && response.data.success) {
          this.stores.push(response.data.store)
        }
        return response.data
      } catch (error) {
        console.error('Failed to create store:', error)
        this.error = error.message
        throw error
      } finally {
        this.loading = false
      }
    },

    async updateStore(id, data) {
      this.loading = true
      this.error = null
      try {
        const response = await axios.put(`/api/stores/${id}`, data)
        if (response.data && response.data.success) {
          const index = this.stores.findIndex(s => s.id === id)
          if (index !== -1) {
            this.stores[index] = response.data.store
          }
        }
        return response.data
      } catch (error) {
        console.error('Failed to update store:', error)
        this.error = error.message
        throw error
      } finally {
        this.loading = false
      }
    },

    async deleteStore(id) {
      this.loading = true
      this.error = null
      try {
        const response = await axios.delete(`/api/stores/${id}`)
        if (response.data && response.data.success) {
          this.stores = this.stores.filter(s => s.id !== id)
        }
        return response.data
      } catch (error) {
        console.error('Failed to delete store:', error)
        this.error = error.message
        throw error
      } finally {
        this.loading = false
      }
    },

    async fetchStoreProducts(storeId) {
      try {
        const response = await axios.get(`/api/stores/${storeId}/products`)
        this.storeProducts = response.data || []
        return this.storeProducts
      } catch (error) {
        console.error('Failed to fetch store products:', error)
        throw error
      }
    },

    async addProductToStore(storeId, productId, quantity, price) {
      try {
        const response = await axios.post(`/api/stores/${storeId}/products`, {
          product_id: productId,
          quantity: quantity,
          price: price
        })
        return response.data
      } catch (error) {
        console.error('Failed to add product to store:', error)
        throw error
      }
    },

    async removeProductFromStore(storeId, productId) {
      try {
        const response = await axios.delete(`/api/stores/${storeId}/products/${productId}`)
        if (response.data && response.data.success) {
          this.storeProducts = this.storeProducts.filter(p => p.product_id !== productId)
        }
        return response.data
      } catch (error) {
        console.error('Failed to remove product from store:', error)
        throw error
      }
    },

    resetCurrentStore() {
      this.currentStore = null
    }
  }
})