// src/client/entities/appConfig.ts
// App configuration entity - Pinia store for managing enabled modules

import { defineStore } from 'pinia';
import { z } from 'zod';
import { api, type RequestConfig } from '../shared/api/api.client';

// Zod schema for API response validation
const EnabledModulesSchema = z.array(z.string());

// Cache duration in milliseconds (5 minutes)
const CACHE_DURATION = 5 * 60 * 1000;

/**
 * App configuration store
 * Manages the list of enabled modules from backend
 */
export const useAppConfigStore = defineStore('appConfig', {
  state: () => ({
    enabledModules: [] as string[],
    isLoading: false as boolean,
    error: null as string | null,
    lastFetchTime: null as number | null,
  }),

  getters: {
    /**
     * Check if a module is enabled
     */
    isModuleEnabled: (state) => (moduleName: string): boolean => {
      return state.enabledModules.includes(moduleName);
    },

    /**
     * Check if config has been loaded and is still fresh
     * Returns false if more than 5 minutes have passed since last fetch
     * or if this is the first session (no modules loaded)
     */
    isLoaded: (state) => {
      // If no modules loaded, consider it not loaded
      if (state.enabledModules.length === 0) {
        return false;
      }
      // If no fetch time recorded, consider it not loaded
      if (state.lastFetchTime === null) {
        return false;
      }
      // Check if cache is stale (more than 5 minutes)
      const isStale = Date.now() - state.lastFetchTime > CACHE_DURATION;
      return !isStale;
    },
  },

  actions: {
    /**
     * Fetch enabled modules from backend
     */
    async fetchConfig(): Promise<void> {
      try {
        this.isLoading = true;
        this.error = null;

        const response = await api.get<string[]>('/config/modules', {
          schema: EnabledModulesSchema,
        } as RequestConfig<string[]>);

        this.enabledModules = response;
        this.lastFetchTime = Date.now();
      } catch (error: any) {
        this.error = error.message || 'Failed to fetch config';
        console.error('[AppConfig] Failed to fetch config:', error);
        throw error;
      } finally {
        this.isLoading = false;
      }
    },

    /**
     * Refresh config from backend
     */
    async refreshConfig(): Promise<void> {
      await this.fetchConfig();
    },

    /**
     * Clear config state
     */
    clearConfig(): void {
      this.enabledModules = [];
      this.error = null;
      this.lastFetchTime = null;
    },
  },

  // Configure persist to exclude lastFetchTime from localStorage
  // This ensures that on page refresh, the config is treated as stale
  persist: {
    key: 'appConfig',
    storage: localStorage,
    pick: ['enabledModules', 'lastFetchTime'], // Only persist enabledModules, not lastFetchTime
  },
});
