import { Offer } from '@/types';
import { resolveMediaUrl } from '@/services/shared/media-url';

const API_BASE = (process.env.NEXT_PUBLIC_AAU_API_BASE_URL || process.env.AAU_API_BASE_URL || 'https://edu.yemenfrappe.com').replace(/\/$/, '');

function unwrapEntityPayload(payload: any) {
  if (payload?.ok && payload?.data !== undefined) {
    return payload.data;
  }
  if (payload?.data?.ok && payload?.data?.data !== undefined) {
    return payload.data.data;
  }
  return payload?.data ?? payload;
}

function mapOffer(item: any): Offer {
  return {
    id: String(item?.id || item?.name || ''),
    titleAr: String(item?.title_ar || item?.titleAr || ''),
    titleEn: String(item?.title_en || item?.titleEn || ''),
    descAr: String(item?.desc_ar || item?.descAr || ''),
    descEn: String(item?.desc_en || item?.descEn || ''),
    image: resolveMediaUrl(item?.image),
    category: item?.category || 'other',
    validUntil: item?.valid_until || item?.validUntil || '',
    detailsAr: String(item?.details_ar || item?.detailsAr || ''),
    detailsEn: String(item?.details_en || item?.detailsEn || ''),
    targetAudienceAr: String(item?.target_audience_ar || item?.targetAudienceAr || ''),
    targetAudienceEn: String(item?.target_audience_en || item?.targetAudienceEn || ''),
    benefitsAr: String(item?.benefits_ar || item?.benefitsAr || ''),
    benefitsEn: String(item?.benefits_en || item?.benefitsEn || ''),
    durationAr: String(item?.duration_ar || item?.durationAr || ''),
    durationEn: String(item?.duration_en || item?.durationEn || ''),
    locationAr: String(item?.location_ar || item?.locationAr || ''),
    locationEn: String(item?.location_en || item?.locationEn || ''),
    requirementsAr: String(item?.requirements_ar || item?.requirementsAr || ''),
    requirementsEn: String(item?.requirements_en || item?.requirementsEn || ''),
    applyLink: String(item?.apply_link || item?.applyLink || ''),
    interestTitleAr: String(item?.interest_title_ar || item?.interestTitleAr || ''),
    interestTitleEn: String(item?.interest_title_en || item?.interestTitleEn || ''),
    interestSubtitleAr: String(item?.interest_subtitle_ar || item?.interestSubtitleAr || ''),
    interestSubtitleEn: String(item?.interest_subtitle_en || item?.interestSubtitleEn || ''),
    interestOpenTitleAr: String(item?.interest_open_title_ar || item?.interestOpenTitleAr || ''),
    interestOpenTitleEn: String(item?.interest_open_title_en || item?.interestOpenTitleEn || ''),
    interestOpenSubtitleAr: String(item?.interest_open_subtitle_ar || item?.interestOpenSubtitleAr || ''),
    interestOpenSubtitleEn: String(item?.interest_open_subtitle_en || item?.interestOpenSubtitleEn || ''),
    interestHighlightsTitleAr: String(item?.interest_highlights_title_ar || item?.interestHighlightsTitleAr || ''),
    interestHighlightsTitleEn: String(item?.interest_highlights_title_en || item?.interestHighlightsTitleEn || ''),
    interestHighlight1Ar: String(item?.interest_highlight_1_ar || item?.interestHighlight1Ar || ''),
    interestHighlight1En: String(item?.interest_highlight_1_en || item?.interestHighlight1En || ''),
    interestHighlight2Ar: String(item?.interest_highlight_2_ar || item?.interestHighlight2Ar || ''),
    interestHighlight2En: String(item?.interest_highlight_2_en || item?.interestHighlight2En || ''),
    interestHighlight3Ar: String(item?.interest_highlight_3_ar || item?.interestHighlight3Ar || ''),
    interestHighlight3En: String(item?.interest_highlight_3_en || item?.interestHighlight3En || ''),
    interestNoticeAr: String(item?.interest_notice_ar || item?.interestNoticeAr || ''),
    interestNoticeEn: String(item?.interest_notice_en || item?.interestNoticeEn || ''),
  };
}

export async function getOffersList(): Promise<Offer[]> {
  try {
    const response = await fetch(`${API_BASE}/api/offers`, {
      headers: { Accept: 'application/json' },
      cache: 'no-store',
    });
    if (!response.ok) {
      return [];
    }
    const payload = await response.json();
    const data = unwrapEntityPayload(payload);
    const items = Array.isArray(data) ? data : Array.isArray(data?.data) ? data.data : [];
    return items.map(mapOffer);
  } catch {
    return [];
  }
}

export async function getOfferById(id: string): Promise<Offer | null> {
  try {
    const response = await fetch(`${API_BASE}/api/offers/${encodeURIComponent(id)}`, {
      headers: { Accept: 'application/json' },
      cache: 'no-store',
    });
    if (!response.ok) {
      return null;
    }
    const payload = await response.json();
    return mapOffer(unwrapEntityPayload(payload));
  } catch {
    return null;
  }
}
