import { defineStore } from 'pinia';
import projectsService from '@/services/projectsService';

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

    actions: {
        async fetchProjects() {
            this.loading = true;
            this.error = null;
            try {
                const response = await projectsService.getProjects();
                this.projects = response.data;
                
                // Restore selection from localStorage if valid
                this.restoreSelection();
            } catch (err) {
                console.error("Failed to fetch projects", err);
                this.error = "Failed to load projects";
            } finally {
                this.loading = false;
            }
        },

        restoreSelection() {
            const savedId = localStorage.getItem('active_project_id');
            if (savedId && this.projects.length > 0) {
                const found = this.projects.find(p => p.id === savedId);
                if (found) {
                    this.currentProject = found;
                } else {
                    // ID exists but project not in list (maybe deleted or lost access)
                    // Optional: clear it or keep it? Clearing seems safer.
                    localStorage.removeItem('active_project_id');
                    this.currentProject = null;
                }
            }
        },

        async createProject(name, description) {
            this.loading = true;
            try {
                const response = await projectsService.createProject({ name, description });
                const newProject = response.data;
                this.projects.push(newProject);
                // Automatically select the new project
                this.selectProject(newProject.id);
                return newProject;
            } catch (err) {
                console.error("Failed to create project", err);
                throw err;
            } finally {
                this.loading = false;
            }
        },

        selectProject(projectId) {
            const project = this.projects.find(p => p.id === projectId);
            if (project) {
                this.currentProject = project;
                localStorage.setItem('active_project_id', projectId);
            }
        },
        
        async addMember(projectId, username) {
            try {
                 await projectsService.addMember(projectId, username);
                 await this.fetchProjects(); // Refresh list to see updates if necessary
            } catch(err) {
                console.error("Failed to add member", err);
                throw err;
            }
        },

        getProjectById(id) {
            return this.projects.find(p => p.id === id);
        },

        async deleteProject(projectId) {
            try {
                await projectsService.deleteProject(projectId);
                this.projects = this.projects.filter(p => p.id !== projectId);
                if (this.currentProject && this.currentProject.id === projectId) {
                    this.currentProject = null;
                    localStorage.removeItem('active_project_id');
                }
            } catch (err) {
                console.error("Failed to delete project", err);
                throw err;
            }
        }
    }
});
