export async function callHA(
  domain: string,
  service: string,
  entity_id: string,
  extra?: Record<string, any>
) {
  const res = await fetch("/api/ha", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ domain, service, entity_id, ...extra }),
  });
  return res.json();
}

export async function toggleLight(entity_id: string, on: boolean) {
  return callHA("light", on ? "turn_on" : "turn_off", entity_id);
}

export async function setLightBrightness(entity_id: string, brightness: number) {
  return callHA("light", "turn_on", entity_id, { brightness });
}

export async function toggleFan(entity_id: string, on: boolean) {
  return callHA("fan", on ? "turn_on" : "turn_off", entity_id);
}

export async function setFanPreset(entity_id: string, preset_mode: string) {
  return callHA("fan", "set_preset_mode", entity_id, { preset_mode });
}

export async function setClimateTemp(entity_id: string, temperature: number) {
  return callHA("climate", "set_temperature", entity_id, { temperature });
}

export async function fetchWeather() {
  const res = await fetch("/api/weather", { next: { revalidate: 600 } });
  return res.json();
}

export async function fetchTasks() {
  const res = await fetch("/api/tasks", { cache: "no-store" });
  return res.json();
}

export async function createTask(title: string) {
  const res = await fetch("/api/tasks", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ title }),
  });
  return res.json();
}

export async function toggleTask(id: number, done: boolean) {
  const res = await fetch("/api/tasks", {
    method: "PATCH",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ id, done }),
  });
  return res.json();
}

export async function fetchSavings() {
  const res = await fetch("/api/savings", { next: { revalidate: 300 } });
  return res.json();
}
