import { dev } from "$app/environment";
import { uuid } from "$lib/stores/uuid";
import type { Unsubscriber } from "svelte/store";

function getUrlString(): string {
    if (dev) {
        const testUrl: string = "http://localhost:8460";
        console.info("DEVMODE active, using testing URL: ", testUrl);
        return testUrl;
    } else {
        const currentUrl: string = `https://${window.location.host}`;
        return currentUrl;
    }
}

export async function apiGet(path: string): Promise<any> {
    let uuidString: string = "";
    let unsubscribe: Unsubscriber;
    try {
        unsubscribe = uuid.subscribe((value) => {
            uuidString = value;
        });
    } catch (err) {
        throw new Error("Unable to read UUID");
    }

    const options = {
        method: "GET",
        headers: {
            uuid: uuidString,
        },
    };

    try {
        const res = await fetch(getUrlString() + path, options);

        if (res.status === 401) {
            throw new Error("Registration not accepted.  Register at `Menu > Registration`");
        }

        if (!res.ok) {
            throw new Error(`Failed: ${res.status}: ${res.statusText}`);
        }
        const contentType = res.headers.get("content-type");
        if (!contentType || !contentType.includes("application/json")) {
            throw new Error("Invalid response.  Require JSON.");
        }
        return await res.json();
    } catch (err) {
        console.error("Error fetching data:", err);
        throw err;
    } finally {
        unsubscribe();
    }
}
