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

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(`${CAM_BASE}/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 = `${CAM_BASE}/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;

    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);
  }
}
