import { toast } from "sonner";
import type { SystemValues } from "../../../types/types";
import { CAM_BASE } from "../../../utils/config";

const camBase = import.meta.env.MODE !== "development" ? CAM_BASE : "";

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

  try {
    const response = await fetch(`${camBase}/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}` : ""}`);
    }
  } catch (err) {
    if (err instanceof Error) {
      toast.error(`Failed to save system settings: ${err.message}`);
      console.error(err);
    } else {
      toast.error("An unexpected error occurred while saving.");
      console.error("Unknown error:", err);
    }
  }
}

export async function handleSystemRecall() {
  const url = `${camBase}/api/fetch-config?id=GLOBAL--Device`;

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

  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;

    const 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) {
    if (err instanceof Error) {
      toast.error(`Error: ${err.message}`);
    } else {
      toast.error("An unexpected error occurred");
    }

    return null;
  } finally {
    clearTimeout(timeoutId);
  }
}
