/**
 * CANIFA STYLIST PRO - API Service
 * Modularized API interactions
 */

const CanifaAPI = {
    getDeviceId: () => {
        let devId = localStorage.getItem('canifa_device_id');
        if (!devId) {
            devId = 'dev-' + Math.random().toString(36).substr(2, 8);
            localStorage.setItem('canifa_device_id', devId);
        }
        return devId;
    },

    getHeaders: (deviceId, token = null) => {
        const headers = {
            'Content-Type': 'application/json',
            'device_id': deviceId
        };
        if (token) {
            headers['Authorization'] = 'Bearer ' + token;
        }
        return headers;
    },

    fetchHistory: async (deviceId, limit = 20) => {
        try {
            const res = await fetch(`/api/history/${deviceId}?limit=${limit}`, {
                headers: CanifaAPI.getHeaders(deviceId)
            });
            return await res.json();
        } catch (e) {
            console.error('History fetch error:', e);
            return { data: [] };
        }
    },

    chat: async (query, deviceId, token = null, dbSource = 'starrocks') => {
        const res = await fetch('/api/agent/chat-dev', {
            method: 'POST',
            headers: CanifaAPI.getHeaders(deviceId, token),
            body: JSON.stringify({ 
                user_query: query, 
                device_id: deviceId,
                config: { configurable: { db_source: dbSource } }
            })
        });
        return await res.json();
    },

    getPrompt: async (type) => {
        const url = type === 'system' ? '/api/agent/system-prompt' : '/api/agent/tool-prompts/lead_search_tool.py';
        const res = await fetch(url);
        return await res.json();
    },

    savePrompt: async (type, content) => {
        const url = type === 'system' ? '/api/agent/system-prompt' : '/api/agent/tool-prompts/lead_search_tool.py';
        const res = await fetch(url, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ content })
        });
        return await res.json();
    },

    archiveHistory: async (deviceId) => {
        return await fetch('/api/history/archive', { 
            method: 'POST', 
            headers: CanifaAPI.getHeaders(deviceId) 
        });
    }
};

window.CanifaAPI = CanifaAPI;
