import { useMemo } from 'react';

import type { Campaign, Ad, CampaignStatus } from '@/types/entities';
import { useData } from '@/providers/data-provider';

type UseCampaignsFilters = {
    status?: CampaignStatus;
};

type UseCampaignsResult = {
    campaigns: Campaign[];
    ads: Ad[];
};

export const useCampaigns = (filters: UseCampaignsFilters = {}): UseCampaignsResult => {
    const { campaigns, ads } = useData();
    const { status } = filters;

    const filteredCampaigns = useMemo(() => {
        if (status === undefined) {
            return campaigns;
        }

        return campaigns.filter((campaign) => campaign.campaignStatus === status);
    }, [campaigns, status]);

    const filteredAds = useMemo(() => {
        const campaignIds = new Set(filteredCampaigns.map((campaign) => campaign.id));

        return ads.filter((ad) => ad.campaignId !== null && campaignIds.has(ad.campaignId));
    }, [ads, filteredCampaigns]);

    return {
        campaigns: filteredCampaigns,
        ads: filteredAds,
    };
};
