import { API_BASE_URL, NoteCategory } from '../types';

export const noteCategoryService = {
    async getAll(token: string): Promise<NoteCategory[]> {
        const res = await fetch(`${API_BASE_URL}/v1/note-categories`, {
            headers: { 'Authorization': `Bearer ${token}` }
        });
        if (!res.ok) throw new Error('Failed to fetch categories');
        return res.json();
    },

    async create(token: string, name: string, parentId?: string): Promise<NoteCategory> {
        const response = await fetch(`${API_BASE_URL}/v1/note-categories`, {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${token}`,
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ name, parentId })
        })
        if (!response.ok) throw new Error('Failed to create category')
        return response.json()
    },

    async update(token: string, id: string, name?: string, parentId?: string): Promise<NoteCategory> {
        const response = await fetch(`${API_BASE_URL}/v1/note-categories/${id}`, {
            method: 'PUT',
            headers: {
                'Authorization': `Bearer ${token}`,
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ name, parentId })
        })
        if (!response.ok) throw new Error('Failed to update category')
        return response.json()
    },

    async delete(token: string, id: string): Promise<void> {
        const res = await fetch(`${API_BASE_URL}/v1/note-categories/${id}`, {
            method: 'DELETE',
            headers: { 'Authorization': `Bearer ${token}` }
        });
        if (!res.ok) throw new Error('Failed to delete category');
    }
};
