import { getToken, authStore } from '$lib/auth';
import { get } from 'svelte/store';

const api_url = import.meta.env.VITE_API_URL ?? '';
const normalizedApiUrl = api_url ? (api_url.endsWith('/') ? api_url : `${api_url}/`) : '/';
const BASE_URL = `${normalizedApiUrl}v1/core/help-center`;

function getAuthToken(): string | null {
    // 1. First try getToken() which checks Keycloak and localStorage
    let token = getToken();

    // 2. If somehow empty, explicitly check authStore value
    if (!token) {
        const auth = get(authStore);
        token = auth.token;
    }

    return token;
}

function getHeaders() {
    const token = getAuthToken();
    return {
        'Content-Type': 'application/json',
        ...(token ? { 'Authorization': `Bearer ${token}` } : {})
    };
}

export interface HelpArticle {
    uuid: string;
    slug: string;
    title: string;
    content: string;
    updated_at: string;
    last_editor: string;
    category?: string;
    order?: number;
    content_type: string;
    file_url?: string;
    file_size?: number;
    mime_type?: string;
    context_path?: string;
    tags?: string;
}

export const helpApi = {
    async listArticles(): Promise<HelpArticle[]> {
        const response = await fetch(`${BASE_URL}/articles/`, { headers: getHeaders() });
        if (!response.ok) throw new Error('Failed to fetch articles');
        return response.json();
    },

    async getArticle(uuid: string): Promise<HelpArticle> {
        const response = await fetch(`${BASE_URL}/articles/${uuid}/`, { headers: getHeaders() });
        if (!response.ok) throw new Error('Failed to fetch article');
        return response.json();
    },

    async updateArticle(uuid: string, data: Partial<HelpArticle>): Promise<HelpArticle> {
        const response = await fetch(`${BASE_URL}/articles/${uuid}/`, {
            method: 'PATCH',
            headers: getHeaders(),
            body: JSON.stringify(data)
        });
        if (response.status === 403) throw new Error('No tienes permisos para editar artículos (Requiere rol Admin)');
        if (!response.ok) throw new Error('Error al guardar cambios');
        return response.json();
    },

    async createArticle(data: Partial<HelpArticle>): Promise<HelpArticle> {
        const response = await fetch(`${BASE_URL}/articles/`, {
            method: 'POST',
            headers: getHeaders(),
            body: JSON.stringify(data)
        });
        if (response.status === 403) throw new Error('No tienes permisos para crear artículos (Requiere rol Admin)');
        if (!response.ok) throw new Error('Error al crear el artículo');
        return response.json();
    },

    async deleteArticle(uuid: string): Promise<void> {
        const response = await fetch(`${BASE_URL}/articles/${uuid}/`, {
            method: 'DELETE',
            headers: getHeaders()
        });
        if (response.status === 403) throw new Error('No tienes permisos para eliminar (Requiere rol Admin)');
        if (!response.ok) throw new Error('Error al eliminar');
    },

    async triggerSync(): Promise<void> {
        // Opcional: endpoint para forzar sync desde UI si es necesario
    },

    async uploadImage(file: File): Promise<{ url: string }> {
        const formData = new FormData();
        formData.append('file', file);

        const token = getAuthToken();
        const response = await fetch(`${BASE_URL}/upload-image/`, {
            method: 'POST',
            // No Content-Type header for FormData, browser sets it with boundary
            headers: {
                ...(token ? { 'Authorization': `Bearer ${token}` } : {})
            },
            body: formData
        });
        if (response.status === 403) throw new Error('No tienes permisos para subir imágenes (Requiere rol Admin)');
        if (!response.ok) throw new Error('Error al subir imagen');
        return response.json();
    },

    async uploadAsset(file: File): Promise<{ url: string, filename: string, size: number, mime_type: string }> {
        const formData = new FormData();
        formData.append('file', file);

        const token = getAuthToken();
        const response = await fetch(`${BASE_URL}/upload-asset/`, {
            method: 'POST',
            headers: {
                ...(token ? { 'Authorization': `Bearer ${token}` } : {})
            },
            body: formData
        });
        if (response.status === 403) throw new Error('No tienes permisos para subir archivos (Requiere rol Admin)');
        if (!response.ok) throw new Error('Error al subir archivo');
        return response.json();
    }
};
