import { defineStore } from 'pinia';
import { ref } from 'vue';
import { apiClient, API_ENDPOINTS } from '@/services/api';

export interface Category {
    id: number;
    name: string;
    user_id?: number | null;
    group_id?: number | null;
}

export interface CategoryCreate {
    name: string;
    group_id?: number;
}

export const useCategoryStore = defineStore('category', () => {
    const categories = ref<Category[]>([]);
    const loading = ref(false);
    const error = ref<string | null>(null);

    async function fetchCategories(groupId?: number) {
        loading.value = true;
        error.value = null;
        try {
            const endpoint = API_ENDPOINTS.CATEGORIES.BASE;
            const params = groupId ? { group_id: groupId } : {};
            const response = await apiClient.get(endpoint, { params });
            categories.value = response.data;
        } catch (e) {
            error.value = 'Failed to fetch categories.';
            console.error(e);
        } finally {
            loading.value = false;
        }
    }

    async function createCategory(categoryData: CategoryCreate) {
        loading.value = true;
        error.value = null;
        try {
            const response = await apiClient.post(API_ENDPOINTS.CATEGORIES.BASE, categoryData);
            categories.value.push(response.data);
        } catch (e) {
            error.value = 'Failed to create category.';
            console.error(e);
        } finally {
            loading.value = false;
        }
    }

    async function updateCategory(id: number, categoryData: Partial<CategoryCreate>) {
        loading.value = true;
        error.value = null;
        try {
            const response = await apiClient.put(API_ENDPOINTS.CATEGORIES.BY_ID(id.toString()), categoryData);
            const index = categories.value.findIndex((c: Category) => c.id === id);
            if (index !== -1) {
                categories.value[index] = response.data;
            }
        } catch (e) {
            error.value = 'Failed to update category.';
            console.error(e);
        } finally {
            loading.value = false;
        }
    }

    async function deleteCategory(id: number) {
        loading.value = true;
        error.value = null;
        try {
            await apiClient.delete(API_ENDPOINTS.CATEGORIES.BY_ID(id.toString()));
            categories.value = categories.value.filter((c: Category) => c.id !== id);
        } catch (e) {
            error.value = 'Failed to delete category.';
            console.error(e);
        } finally {
            loading.value = false;
        }
    }

    return {
        categories,
        loading,
        error,
        fetchCategories,
        createCategory,
        updateCategory,
        deleteCategory,
    };
}); 