export async function handleSystemSave(deviceName: string, sntpServer: string, sntpInterval: number, timeZone: string) {
    const payload = { // Build JSON
        id: "GLOBAL--Device",
        fields: [
        { property: "propDeviceName",            value: deviceName },
        { property: "propSNTPServer",            value: sntpServer },
        { property: "propSNTPIntervalMinutes",   value: Number(sntpInterval) },
        { property: "propLocalTimeZone",         value: timeZone }
        ]
    };

    try {
        const response = await fetch("http://192.168.75.11/api/update-config", {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
            "Accept": "application/json"
        },
        body: JSON.stringify(payload)
        });

        if (!response.ok) {
        const text = await response.text().catch(() => "");
        throw new Error(`HTTP ${response.status} ${response.statusText}${text ? ` - ${text}` : ""}`);
        }

        alert("System Settings Saved Successfully!");
    } catch (err) {
        console.error(err);
    }
}

export async function handleSystemRecall() {
    const url = "http://192.168.75.11/api/fetch-config?id=GLOBAL--Device";

    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), 7000);

    try {
        const response = await fetch(url, {
        method: "GET",
        headers: { "Accept": "application/json" },
        signal: controller.signal
        });

        if (!response.ok) {
        const text = await response.text().catch(() => "");
        throw new Error(`HTTP ${response.status} ${response.statusText}${text ? ` - ${text}` : ""}`);
        }

        const data = await response.json();

        const deviceName = data?.propDeviceName?.value ?? null;
        const sntpServer = data?.propSNTPServer?.value ?? null;
        const timeZone = data?.propLocalTimeZone?.value ?? null;

        let sntpIntervalRaw = data?.propSNTPIntervalMinutes?.value;
        let sntpInterval =
        typeof sntpIntervalRaw === "number"
            ? sntpIntervalRaw
            : Number.parseInt(String(sntpIntervalRaw).trim(), 10);

        if (!Number.isFinite(sntpInterval)) {
            sntpInterval = 60;
        }

        return { deviceName, sntpServer, sntpInterval, timeZone };
    } catch (err) {
        console.error(err);
        return null;
    } finally {
        clearTimeout(timeoutId);
    }
}