import { BookProject, UserProfile } from './types';

const API_BASE_URL = '/api';

// --- API CLIENT ---

const api = {
    async request<T = any>(endpoint: string, options: RequestInit = {}) {
        const url = `${API_BASE_URL}${endpoint}`;

        const headers: Record<string, string> = {
            'Content-Type': 'application/json',
            ...options.headers as Record<string, string>,
        };

        const response = await fetch(url, {
            ...options,
            headers,
        });

        if (!response.ok) {
            let errorMsg = `Error ${response.status}: ${response.statusText}`;
            try {
                const errorJson = await response.json();
                if (errorJson.error) errorMsg = errorJson.error;
                if (errorJson.message) errorMsg = errorJson.message;
            } catch {
                // Ignore json parse error
            }
            throw new Error(errorMsg);
        }

        if (response.status === 204) return null;
        return response.json();
    },

    // --- AUTH ---
    auth: {
        async register(email: string, password: string, name: string) {
            return api.request('/auth/register', {
                method: 'POST',
                body: JSON.stringify({ email, password, name }),
            });
        },
    },

    // --- USER ---
    user: {
        async updateProfile(data: any) {
            return api.request('/user/profile', {
                method: 'PUT',
                body: JSON.stringify(data),
            });
        },
    },

    // --- PROJECTS ---
    projects: {
        async list() {
            return api.request<any[]>('/projects');
        },

        async get(id: string) {
            return api.request<any>(`/projects/${id}`);
        },

        async create(data: { title: string; author: string; settings?: any }) {
            return api.request<any>('/projects', {
                method: 'POST',
                body: JSON.stringify(data),
            });
        },

        async update(id: string, data: any) {
            return api.request<any>(`/projects/${id}`, {
                method: 'PUT',
                body: JSON.stringify(data),
            });
        },

        async delete(id: string) {
            return api.request(`/projects/${id}`, {
                method: 'DELETE',
            });
        },

        async syncWorkflow(id: string, data: { nodes: any[]; connections: any[] }) {
            return api.request(`/projects/${id}/workflow`, {
                method: 'PUT',
                body: JSON.stringify(data),
            });
        },
    },

    // --- CHAPTERS ---
    chapters: {
        async create(data: { projectId: string; title?: string; content?: string; summary?: string; orderIndex?: number }) {
            return api.request<any>('/chapters', {
                method: 'POST',
                body: JSON.stringify(data),
            });
        },

        async update(id: string, data: any) {
            return api.request<any>(`/chapters/${id}`, {
                method: 'PUT',
                body: JSON.stringify(data),
            });
        },

        async delete(id: string) {
            return api.request(`/chapters/${id}`, {
                method: 'DELETE',
            });
        },
    },

    // --- ENTITIES ---
    entities: {
        async create(data: { projectId: string; type: string; name?: string; description?: string; details?: string; attributes?: any; customValues?: any }) {
            return api.request<any>('/entities', {
                method: 'POST',
                body: JSON.stringify(data),
            });
        },

        async update(id: string, data: any) {
            return api.request<any>(`/entities/${id}`, {
                method: 'PUT',
                body: JSON.stringify(data),
            });
        },

        async delete(id: string) {
            return api.request(`/entities/${id}`, {
                method: 'DELETE',
            });
        },
    },

    // --- IDEAS ---
    ideas: {
        async create(data: { projectId: string; title?: string; description?: string; status?: string; category?: string }) {
            return api.request<any>('/ideas', {
                method: 'POST',
                body: JSON.stringify(data),
            });
        },

        async update(id: string, data: any) {
            return api.request<any>(`/ideas/${id}`, {
                method: 'PUT',
                body: JSON.stringify(data),
            });
        },

        async delete(id: string) {
            return api.request(`/ideas/${id}`, {
                method: 'DELETE',
            });
        },
    },

    // --- AI (server-side via API routes) ---
    ai: {
        async generate(project: BookProject, chapterId: string, prompt: string, user: UserProfile) {
            return api.request<{ text: string; type: 'draft' | 'reflection' }>('/ai/generate', {
                method: 'POST',
                body: JSON.stringify({ project, chapterId, prompt, user }),
            });
        },

        async transform(text: string, mode: string, context: string, user: UserProfile) {
            const res = await api.request<{ text: string }>('/ai/transform', {
                method: 'POST',
                body: JSON.stringify({ text, mode, context, user }),
            });
            return res.text;
        },
    },
};

export default api;
