import { FAQItem } from '@/types';

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

function unwrapPayload(payload: any) {
  if (payload?.ok && payload?.data) {
    return payload.data;
  }
  if (payload?.data?.ok && payload?.data?.data) {
    return payload.data.data;
  }
  return payload?.data || payload;
}

function mapFaq(item: any, index: number): FAQItem {
  const id = String(item?.id || item?.docname || index + 1);
  const title = String(item?.title || '');
  const content = String(item?.content || '');

  return {
    id,
    questionAr: String(item?.questionAr || item?.question_ar || ''),
    questionEn: String(item?.questionEn || item?.question_en || title),
    answerAr: String(item?.answerAr || item?.answer_ar || ''),
    answerEn: String(item?.answerEn || item?.answer_en || content),
    category: String(item?.category || ''),
  };
}

export async function getFaqList(): Promise<FAQItem[]> {
  try {
    const response = await fetch(`${API_BASE}/api/faqs`, {
      headers: { Accept: 'application/json' },
      cache: 'no-store',
    });

    if (!response.ok) {
      return [];
    }

    const payload = await response.json();
    const items = unwrapPayload(payload);
    return Array.isArray(items) ? items.map(mapFaq) : [];
  } catch {
    return [];
  }
}
