import { FiltersData, Programme } from '../types/programme'; /** * Lấy API URL từ environment variable */ const getApiUrl = (): string | null => { const apiUrl = process.env.NEXT_PUBLIC_API_URL; if (!apiUrl) return null; return apiUrl; }; /** * Fetch tất cả programmes từ API, trả về null nếu thất bại */ export const fetchProgrammes = async (): Promise => { const apiUrl = getApiUrl(); if (!apiUrl) return null; const url = `${apiUrl}/api/programmes`; try { const response = await fetch(url, { method: 'GET', headers: { 'Content-Type': 'application/json' }, cache: 'no-store', }); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const data: Programme[] = await response.json(); return data; } catch { return null; } }; /** * Fetch một programme theo id/slug, trả về null nếu thất bại */ export const fetchProgrammeById = async (id: string): Promise => { const apiUrl = getApiUrl(); if (!apiUrl) return null; const url = `${apiUrl}/api/programmes/${id}`; try { const response = await fetch(url, { method: 'GET', headers: { 'Content-Type': 'application/json' }, cache: 'no-store', }); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const data: Programme = await response.json(); return data; } catch { return null; } }; /** * Fetch những programmes được đánh dấu featured (selected: true) * trả về null nếu thất bại */ export const fetchFeaturedProgrammes = async (): Promise => { const data = await fetchProgrammes(); if (!data) return null; return data.filter((p) => p.selected === true); }; /** * Fetch programme filter options from CMS. */ export const fetchProgrammeFilters = async (): Promise => { const apiUrl = getApiUrl(); if (!apiUrl) return null; const url = `${apiUrl}/api/programmes/filters`; try { const response = await fetch(url, { method: 'GET', headers: { 'Content-Type': 'application/json' }, cache: 'no-store', }); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const data: FiltersData = await response.json(); return data; } catch { return null; } };