export interface Document {
    id: string;
    tenant_id: string;
    parent_id: string | null;
    title: string;
    content: string; // JSON String for blocks
    status: 'draft' | 'published';
    created_by: string;
    last_updated_by: string;
    version: number;
    created_at: string;
    updated_at: string;
}

export interface DocumentActivity {
    id: string;
    document_id: string;
    user_id: string;
    user_name: string;
    action: string;
    description: string;
    created_at: string;
}

const BASE_URL = '/api/documents';

async function fetchWithAuth(url: string, options: RequestInit = {}) {
    const token = localStorage.getItem('token');
    const response = await fetch(url, {
        cache: 'no-store',
        ...options,
        headers: {
            ...options.headers,
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json',
        },
    });
    if (!response.ok) {
        throw new Error(`API error: ${response.status}`);
    }
    if (response.status === 204) return null;

    const text = await response.text();
    if (!text) return null;

    try {
        const data = JSON.parse(text);
        return data === null ? [] : data;
    } catch (e) {
        console.error('Failed to parse API response:', text);
        return null;
    }
}

export const docApi = {
    getDocuments: () => fetchWithAuth(BASE_URL),
    getDocument: (id: string) => fetchWithAuth(`${BASE_URL}/${id}`),
    getSubpages: (id: string) => fetchWithAuth(`${BASE_URL}/${id}/subpages`),
    getActivities: (id: string) => fetchWithAuth(`${BASE_URL}/${id}/activities`),
    createDocument: (data: Partial<Document>) => fetchWithAuth(BASE_URL, { method: 'POST', body: JSON.stringify(data) }),
    updateDocument: (id: string, data: Partial<Document>) => fetchWithAuth(`${BASE_URL}/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
    deleteDocument: (id: string) => fetchWithAuth(`${BASE_URL}/${id}`, { method: 'DELETE' }),
};
