import { useEffect, useState } from 'react';
import { apiClient } from '@/lib/api-client';

// Per-tenant UI flags the sidecar controls via env vars. Read once at
// app mount; cached in module scope so every consumer gets the same
// snapshot without re-fetching. Safe defaults when the sidecar doesn't
// respond (all flags off) so the UI stays functional.
export type UiFlags = {
    setupManaged: boolean;
};

const DEFAULT_FLAGS: UiFlags = {
    setupManaged: false,
};

let cachedFlags: UiFlags | null = null;
let inflight: Promise<UiFlags> | null = null;

export const getUiFlags = (): Promise<UiFlags> => fetchFlags();

const fetchFlags = (): Promise<UiFlags> => {
    if (cachedFlags) return Promise.resolve(cachedFlags);
    if (inflight) return inflight;
    inflight = apiClient
        .get<UiFlags>('/api/config/ui-flags', { silent: true })
        .then((res) => {
            cachedFlags = { ...DEFAULT_FLAGS, ...res };
            return cachedFlags;
        })
        .catch(() => {
            cachedFlags = { ...DEFAULT_FLAGS };
            return cachedFlags;
        })
        .finally(() => {
            inflight = null;
        });
    return inflight;
};

export const useUiFlags = (): UiFlags => {
    const [flags, setFlags] = useState<UiFlags>(cachedFlags ?? DEFAULT_FLAGS);
    useEffect(() => {
        if (cachedFlags) {
            setFlags(cachedFlags);
            return;
        }
        fetchFlags().then(setFlags);
    }, []);
    return flags;
};
