importScripts("./API.js");

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    if (message.action === "updateHorseData") {
        // Kein async/await mehr in diesem Aufruf
        updateHorseButton();
    }
    // Kein return true erforderlich, da wir kein asynchrones sendResponse nutzen
});

function sendMessageAsync(tabId, message) {
    return new Promise((resolve, reject) => {
        chrome.tabs.sendMessage(tabId, message, (response) => {
            if (chrome.runtime.lastError) {
                reject(new Error(chrome.runtime.lastError.message));
            } else {
                resolve(response);
            }
        });
    });
}

function updateHorseButton() {
    console.log("Updating horse data");

    // Aktiven Tab ermitteln
    new Promise((resolve) => {
        chrome.tabs.query({ active: true, currentWindow: true }, resolve);
    })
    .then((tabs) => {
        if (!tabs || tabs.length === 0) {
            console.error("No active tab found.");
            return; // Beende die Kette
        }

        const activeTabId = tabs[0].id;

        // Schritt 1: Basisdaten des Pferdes holen
        return sendMessageAsync(activeTabId, { action: "getHorseBasicData" })
            .then((basicDataResponse) => {
                if (!basicDataResponse || !basicDataResponse.success) {
                    console.error("Failed to get horse basic data:", basicDataResponse ? basicDataResponse.message : "No response");
                    return; // Beende die Kette
                }
                console.log("Horse data received:", basicDataResponse.data);
                const horseData = basicDataResponse.data;

                // Pferd beim Backend prüfen
                return getHorseLoadStateAPIAsync(horseData.id)
                    .then((existingHorse) => {
                        if (!existingHorse || existingHorse.message === "Horse not found") {
                            console.warn("Horse not found in the API.");
                            return; // Beende die Kette
                        }

                        // Basisdaten an die API senden
                        return setBaseDataHorseAPI(horseData.id, horseData)
                            .then(() => {
                                console.log("Base data updated in API for horse ID:", horseData.id);
                                // Schritt 2: Aktuelle Horse-Daten holen (abhängig vom aktiven Tab)
                                return sendMessageAsync(activeTabId, { action: "getHorseCurrentData", data: { id: horseData.id } })
                                    .then((currentDataResponse) => {
                                        if (!currentDataResponse.success) {
                                            console.error("Failed to get current horse data. Error:", currentDataResponse.message);
                                            return;
                                        }

                                        console.log("Current horse data received:", currentDataResponse.data);
                                    });
                            });
                    });
            });
    })
    .catch((error) => {
        console.error("Error in updateHorseButton:", error);
    });
}
