<script lang="ts">
  import { onMount, onDestroy } from "svelte";
  import { goto } from "$app/navigation";
  import { clientFetch, ClientFetchError } from "$lib/client-fetch";

  const INTERVAL_MS = 60_000; // 60 seconds

  let timer: ReturnType<typeof setInterval> | null = null;

  async function checkSession() {
    try {
      await clientFetch("/api/auth/check");
    } catch (err) {
      if (err instanceof ClientFetchError && err.status === 401) {
        // Session is dead — redirect to login
        console.warn("Session expired or invalid — redirecting to login.");
        goto("/login");
        return;
      }
      // Network error (API unreachable, etc.) — don't redirect on transient
      // failures; the next tick will retry.
      console.warn("Session check failed (network error):", err);
    }
  }

  onMount(() => {
    // Run the first check immediately, then every 60 s
    checkSession();
    timer = setInterval(checkSession, INTERVAL_MS);
  });

  onDestroy(() => {
    if (timer) {
      clearInterval(timer);
      timer = null;
    }
  });
</script>
