import { defineStore } from 'pinia';
import { projectsApi } from '../api/projects.js';
import { useWorkspaceStore } from './workspace.js';

export const useProjectsStore = defineStore('projects', {
  state: () => ({
    projects: [],
    loading: false,
    error: null,
  }),

  actions: {
    async fetchProjects() {
      const workspaceStore = useWorkspaceStore();
      if (!workspaceStore.currentWorkspaceId) return;

      this.loading = true;
      try {
        const response = await projectsApi.list(workspaceStore.currentWorkspaceId);
        this.projects = response.projects || [];
      } catch (err) {
        this.error = err.message;
      } finally {
        this.loading = false;
      }
    },

    async createProject(name, description = '') {
      const workspaceStore = useWorkspaceStore();
      if (!workspaceStore.currentWorkspaceId) return;

      try {
        const project = await projectsApi.create(workspaceStore.currentWorkspaceId, name, description);
        this.projects.unshift(project);
        return project;
      } catch (err) {
        this.error = err.message;
        throw err;
      }
    },

    async updateProject(id, data) {
      const workspaceStore = useWorkspaceStore();
      if (!workspaceStore.currentWorkspaceId) return;

      try {
        const project = await projectsApi.update(workspaceStore.currentWorkspaceId, id, data);
        const index = this.projects.findIndex(p => p.id === id);
        if (index !== -1) {
          this.projects[index] = project;
        }
        return project;
      } catch (err) {
        this.error = err.message;
        throw err;
      }
    },

    async deleteProject(id) {
      const workspaceStore = useWorkspaceStore();
      if (!workspaceStore.currentWorkspaceId) return;

      try {
        await projectsApi.delete(workspaceStore.currentWorkspaceId, id);
        this.projects = this.projects.filter(p => p.id !== id);
      } catch (err) {
        this.error = err.message;
        throw err;
      }
    },

    clearAll() {
      this.projects = [];
    },
  },
});
