import { defineStore } from 'pinia';
import { analyticsApi } from '../api/analytics.js';
import { useWorkspaceStore } from './workspace.js';

export const useAnalyticsStore = defineStore('analytics', {
  state: () => ({
    analytics: null,
    loading: false,
    error: null,
  }),

  actions: {
    async fetchAnalytics(period = '7d', startDate = null, endDate = null) {
      const workspaceStore = useWorkspaceStore();
      if (!workspaceStore.currentWorkspaceId) return;

      this.loading = true;
      try {
        this.analytics = await analyticsApi.getWorkspaceAnalytics(
          workspaceStore.currentWorkspaceId,
          period,
          startDate,
          endDate
        );
      } catch (err) {
        this.error = err.message;
      } finally {
        this.loading = false;
      }
    },

    clearAll() {
      this.analytics = null;
    },
  },
});
