import { useEffect, useState } from 'react';
import type { PromotionCaseForLink, PromotionForLink } from '@/utils/orderPromotionLink';

export type RunningPromotion = PromotionForLink & {
    promotion_case: PromotionCaseForLink[];
};

export function useRunningPromotions() {
    const [promotions, setPromotions] = useState<RunningPromotion[]>([]);
    const [isLoading, setIsLoading] = useState(true);

    useEffect(() => {
        const fetchRunningPromotions = async () => {
            setIsLoading(true);
            try {
                const api_url = process.env.API_URL;
                const response = await fetch(`${api_url}api/promotions/running`, {
                    method: 'GET',
                    headers: { 'Content-Type': 'application/json' },
                    credentials: 'include',
                });

                if (response.ok) {
                    const data = await response.json();
                    setPromotions(Array.isArray(data) ? data : []);
                } else {
                    setPromotions([]);
                }
            } catch (error) {
                console.error('Failed to fetch running promotions:', error);
                setPromotions([]);
            } finally {
                setIsLoading(false);
            }
        };

        void fetchRunningPromotions();
    }, []);

    return { promotions, isLoading };
}
