/**
 * InsightReply Background Script
 * 负责中转消息、管理 OAuth 以及与 Go 后端 API 通信
 */

console.log('InsightReply Background Script Loaded');

const API_BASE = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080/api/v1';

chrome.runtime.onMessage.addListener((message: { type: string; payload?: any }, _sender: chrome.runtime.MessageSender, sendResponse: (response?: any) => void) => {
    if (message.type === 'SHOW_INSIGHT') {
        console.log('[InsightReply Background] Received SHOW_INSIGHT data:', message.payload);
        if (_sender.tab?.id) {
            console.log(`[InsightReply Background] Forwarding SHOW_INSIGHT to tab ${_sender.tab.id}`);
            chrome.tabs.sendMessage(_sender.tab.id, message, (response) => {
                if (chrome.runtime.lastError) {
                    console.error('[InsightReply Background] Error forwarding message to tab:', chrome.runtime.lastError);
                } else {
                    console.log('[InsightReply Background] Successfully forwarded to tab, response:', response);
                }
            });
        }
        sendResponse({ success: true, forwarded: !!_sender.tab?.id });
        return true;
    }

    if (message.type === 'FETCH_CUSTOM_STRATEGIES') {
        chrome.storage.local.get(['jwt_token'], (res) => {
            const token = res.jwt_token;
            if (!token) {
                sendResponse({ success: false, data: [] });
                return;
            }

            fetch(`${API_BASE}/users/me/strategies`, {
                headers: { 'Authorization': `Bearer ${token}` }
            })
                .then(resp => resp.json())
                .then(data => {
                    if (data.code === 200 && Array.isArray(data.data)) {
                        sendResponse({ success: true, data: data.data });
                    } else {
                        sendResponse({ success: false, data: [] });
                    }
                })
                .catch(err => {
                    console.error('Fetch strategies error:', err);
                    sendResponse({ success: false, data: [] });
                });
        });
        return true;
    }

    if (message.type === 'GENERATE_REPLY') {
        const { tweetContent, strategy, identity } = message.payload;

        chrome.storage.local.get(['jwt_token'], (res) => {
            const token = res.jwt_token;
            if (!token) {
                sendResponse({ success: false, error: 'unauthorized', message: 'Please log in via the Extension Options page.' });
                return;
            }

            fetch(`${API_BASE}/ai/generate`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
                body: JSON.stringify({
                    tweet_content: tweetContent,
                    strategy: strategy,
                    identity: identity || 'Independent Developer / Founder'
                })
            })
                .then(resp => resp.json())
                .then(data => {
                    const resultData = data.data;
                    sendResponse({ success: true, data: resultData });

                    // Save to History Tab
                    if (resultData && resultData.replies) {
                        chrome.storage.local.get(['history'], (res) => {
                            const history = Array.isArray(res.history) ? res.history : [];
                            const newEntry = {
                                timestamp: Date.now(),
                                tweetContent,
                                replies: resultData.replies
                            };
                            const updatedHistory = [newEntry, ...history].slice(0, 50); // Keep last 50
                            chrome.storage.local.set({ history: updatedHistory });
                        });
                    }
                })
                .catch(err => {
                    console.error('API Error:', err);
                    sendResponse({ success: false, error: err.message });
                });

        });

        return true; // Keep channel open for async response
    }
    return true;
});
