import Server from './Server';

const SELECTED_CAMPAIGN_KEY = 'selectedCampaignId';

export const useCampaignService = () => {
  const Campaign = useState('campaign', () => null)

  const SetCampaign = (data) => {
    Campaign.value = data;
    if (data?._id) {
      localStorage.setItem(SELECTED_CAMPAIGN_KEY, data._id);
    } else {
      localStorage.removeItem(SELECTED_CAMPAIGN_KEY);
    }
  }

  const RestoreCampaign = async () => {
    const campaignId = localStorage.getItem(SELECTED_CAMPAIGN_KEY);
    if (!campaignId) return false;

    try {
      const response = await Server().get(`/campaign/retrieve/${campaignId}`);
      if (response.data.status !== 'ok') {
        SetCampaign(null);
        return false;
      }

      SetCampaign(response.data.campaign);
      return true;
    } catch (error) {
      SetCampaign(null);
      return false;
    }
  }

  return {
    Campaign,
    SetCampaign,
    RestoreCampaign
  }
}
