"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";

interface GenerationStatus {
  id: string;
  status: "queued" | "processing" | "done" | "error";
  imageUrl?: string | null;
}

export function useGenerationStatus(jobId: string, initialStatus: string) {
  const [status, setStatus] = useState(initialStatus);
  const [imageUrl, setImageUrl] = useState<string | null>(null);
  const router = useRouter();

  useEffect(() => {
    // Don't poll if already done or error
    if (status === "done" || status === "error") {
      return;
    }

    const pollStatus = async () => {
      try {
        // Use server-side API route that can access HttpOnly cookies
        const response = await fetch(`/api/generations/${jobId}/status`, {
          method: "GET",
          cache: "no-store",
        });

        if (!response.ok) {
          throw new Error("Failed to fetch status");
        }

        const data: GenerationStatus = await response.json();

        // Check if status changed to "done"
        const wasProcessing = status === "processing" || status === "queued";
        const isDoneNow = data.status === "done";

        setStatus(data.status);

        if (data.status === "done" && data.imageUrl) {
          setImageUrl(data.imageUrl);

          // Refresh the page cache to update dashboard data
          if (wasProcessing && isDoneNow) {
            router.refresh();
          }
        }
      } catch {
        // Silently fail - don't break UI if polling fails
        setStatus("error");
      }
    };

    // Poll immediately
    pollStatus();

    // Then poll every 5 seconds
    const interval = setInterval(pollStatus, 5000);

    return () => clearInterval(interval);
  }, [jobId, status, router]);

  return { status, imageUrl };
}
