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

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

const API_BASE = '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('Received tweet data in background:', message.payload);
    }

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

        fetch(`${API_BASE}/ai/generate`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                tweet_content: tweetContent,
                strategy: strategy,
                identity: identity || 'Independent Developer / Founder'
            })
        })
            .then(resp => resp.json())
            .then(data => {
                sendResponse({ success: true, data: data.data });
            })
            .catch(err => {
                console.error('API Error:', err);
                sendResponse({ success: false, error: err.message });
            });

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