import { useEffect, useState } from 'react';
import PropTypes from 'prop-types';

export default function ThalosTokenConnector({ googleIdToken, onSuccess, onError }) {
    const [loading, setLoading] = useState(false);

    useEffect(() => {
        if (!googleIdToken) return;

        let cancelled = false;
        const run = async () => {
            setLoading(true);
            try {
                const res = await fetch(
                    'https://thalos-bff.dream-views.com/api/v1/Authentication/GenerateToken',
                    {
                        method: 'GET',
                        headers: {
                            Accept: 'application/json',
                            Authorization: `Bearer ${googleIdToken}`,
                        },
                    }
                );

                if (!res.ok) {
                    const text = await res.text();
                    throw new Error(`Auth exchange failed (${res.status}): ${text || 'No details'}`);
                }

                const payload = await res.json();
                if (cancelled) return;

                if (payload?.token) {
                    localStorage.setItem('thalosToken', payload.token);
                }

                onSuccess?.(payload);
            } catch (err) {
                if (!cancelled) onError?.(err);
                console.error('Thalos token exchange error:', err);
            } finally {
                if (!cancelled) setLoading(false);
            }
        };

        run();
        return () => {
            cancelled = true;
        };
    }, [googleIdToken, onSuccess, onError]);

    return null;
}

ThalosTokenConnector.propTypes = {
    googleIdToken: PropTypes.string.isRequired,
    onSuccess: PropTypes.func,
    onError: PropTypes.func,
};