import { useEffect, useState } from 'react';
import { api } from '@/api/client';
import type { GitMeta } from '@/api/types';

const POLL_INTERVAL_MS = 30_000;

// Live-ish git meta for the project header indicator. Backed by the server's
// 30s cache, so a 30s client poll plus the cache TTL bounds total staleness
// to ~60s in the worst case. Returns null while the first fetch is in flight
// or if the request failed.
export function useProjectGit(projectId: string | null | undefined): GitMeta | null {
  const [meta, setMeta] = useState<GitMeta | null>(null);

  useEffect(() => {
    if (!projectId) {
      setMeta(null);
      return;
    }
    let cancelled = false;

    const fetchOnce = () => {
      api.projects
        .git(projectId)
        .then((m) => {
          if (!cancelled) setMeta(m);
        })
        .catch(() => {
          if (!cancelled) setMeta(null);
        });
    };

    fetchOnce();
    const t = setInterval(fetchOnce, POLL_INTERVAL_MS);
    return () => {
      cancelled = true;
      clearInterval(t);
    };
  }, [projectId]);

  return meta;
}
