import { defineStore } from 'pinia';
import { workspacesApi } from '../api/workspaces.js';

export const useWorkspaceStore = defineStore('workspace', {
  state: () => ({
    workspaces: [],
    currentWorkspace: null,
    loading: false,
    error: null,
    initialized: false,
  }),

  getters: {
    currentWorkspaceId: (state) => state.currentWorkspace?.id,
    currentPlan: (state) => state.currentWorkspace?.plan || 'Free',
    canUseCustomDomains: (state) => {
      const plan = state.currentWorkspace?.plan;
      return plan === 'Pro' || plan === 'Business';
    },
  },

  actions: {
    async initialize() {
      if (this.initialized) return;
      await this.fetchWorkspaces();
      this.initialized = true;
    },

    async fetchWorkspaces() {
      this.loading = true;
      try {
        const response = await workspacesApi.list();
        this.workspaces = response.workspaces || [];

        const savedId = localStorage.getItem('currentWorkspaceId');
        const saved = savedId ? this.workspaces.find(w => w.id === savedId) : null;

        if (saved) {
          this.currentWorkspace = saved;
        } else if (this.workspaces.length > 0) {
          this.setCurrentWorkspace(this.workspaces[0]);
        }
      } catch (err) {
        this.error = err.message;
      } finally {
        this.loading = false;
      }
    },

    setCurrentWorkspace(workspace) {
      this.currentWorkspace = workspace;
      if (workspace) {
        localStorage.setItem('currentWorkspaceId', workspace.id);
      } else {
        localStorage.removeItem('currentWorkspaceId');
      }
    },

    async createWorkspace(name) {
      try {
        const workspace = await workspacesApi.create(name);
        this.workspaces.push(workspace);
        return workspace;
      } catch (err) {
        this.error = err.message;
        throw err;
      }
    },

    async updateWorkspace(id, name) {
      try {
        const updated = await workspacesApi.update(id, name);
        const index = this.workspaces.findIndex(w => w.id === id);
        if (index !== -1) {
          this.workspaces[index] = updated;
        }
        if (this.currentWorkspace?.id === id) {
          this.currentWorkspace = updated;
        }
        return updated;
      } catch (err) {
        this.error = err.message;
        throw err;
      }
    },

    async deleteWorkspace(id) {
      try {
        await workspacesApi.delete(id);
        this.workspaces = this.workspaces.filter(w => w.id !== id);
        if (this.currentWorkspace?.id === id) {
          this.setCurrentWorkspace(this.workspaces[0] || null);
        }
      } catch (err) {
        this.error = err.message;
        throw err;
      }
    },

    clearAll() {
      this.workspaces = [];
      this.currentWorkspace = null;
      this.initialized = false;
      localStorage.removeItem('currentWorkspaceId');
    },
  },
});
