/**
 * Pinia Store pentru Cache Management
 */
import { defineStore } from "pinia";
import api from "@reports/services/api";

export const useCacheStore = defineStore("cache", {
  state: () => ({
    stats: null,
    loading: false,
    error: null,
  }),

  getters: {
    isLoading: (state) => state.loading,
    hasError: (state) => state.error !== null,
    cacheEnabled: (state) => state.stats?.enabled ?? false,
    hitRate: (state) => state.stats?.hit_rate ?? 0,
    queriesSaved: (state) =>
      state.stats?.queries_saved ?? { today: 0, week: 0, total: 0 },
    responseTimes: (state) => state.stats?.response_times ?? {},
    cacheSize: (state) => state.stats?.cache_size ?? { memory: 0, sqlite: 0 },
  },

  actions: {
    /**
     * Get cache statistics
     */
    async getStats() {
      this.loading = true;
      this.error = null;

      try {
        const response = await api.get("/cache/stats");
        this.stats = response.data;
        return response.data;
      } catch (error) {
        this.error = error.response?.data?.detail || error.message;
        throw error;
      } finally {
        this.loading = false;
      }
    },

    /**
     * Invalidate cache
     * @param {number|null} companyId - Optional company ID to invalidate
     * @param {string|null} cacheType - Optional cache type to invalidate
     */
    async invalidateCache(companyId = null, cacheType = null) {
      this.loading = true;
      this.error = null;

      try {
        const response = await api.post("/cache/invalidate", {
          company_id: companyId,
          cache_type: cacheType,
        });

        return response.data;
      } catch (error) {
        this.error = error.response?.data?.detail || error.message;
        throw error;
      } finally {
        this.loading = false;
      }
    },

    /**
     * Toggle user cache setting
     * @param {boolean} enabled - Enable or disable cache for current user
     */
    async toggleUserCache(enabled) {
      this.loading = true;
      this.error = null;

      try {
        const response = await api.post("/cache/toggle-user", {
          enabled,
        });

        // Update local stats
        if (this.stats) {
          this.stats.user_enabled = enabled;
        }

        return response.data;
      } catch (error) {
        this.error = error.response?.data?.detail || error.message;
        throw error;
      } finally {
        this.loading = false;
      }
    },

    /**
     * Toggle global cache (admin only)
     * @param {boolean} enabled - Enable or disable cache globally
     */
    async toggleGlobalCache(enabled) {
      this.loading = true;
      this.error = null;

      try {
        const response = await api.post("/cache/toggle-global", {
          enabled,
        });

        // Update local stats
        if (this.stats) {
          this.stats.global_enabled = enabled;
          this.stats.enabled = enabled;
        }

        return response.data;
      } catch (error) {
        this.error = error.response?.data?.detail || error.message;
        throw error;
      } finally {
        this.loading = false;
      }
    },

    /**
     * Toggle auto-invalidation monitoring
     * @param {boolean} enabled - Enable or disable auto-invalidation
     */
    async toggleAutoInvalidate(enabled) {
      this.loading = true;
      this.error = null;

      try {
        const response = await api.post(
          "/cache/toggle-auto-invalidate",
          { enabled },
        );

        // Update local stats
        if (this.stats) {
          this.stats.auto_invalidate = enabled;
        }

        return response.data;
      } catch (error) {
        this.error = error.response?.data?.detail || error.message;
        throw error;
      } finally {
        this.loading = false;
      }
    },

    /**
     * Clear error state
     */
    clearError() {
      this.error = null;
    },
  },
});
