import { CoursesProps, CoursesArrayProps, SettingsProps, MessageProps } from "@/types"; export async function postMessage(data: MessageProps) { const headers: HeadersInit = { "Accept": "application/json", "Content-Type": "application/json", }; const body = JSON.stringify(data); const url = `http://localhost/api/v1/messages/`; try { const response = await fetch(url, { method: "POST", headers, body, }); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const contentType = response.headers.get("content-type"); if (contentType && contentType.indexOf("application/json") !== -1) { return { success: true } } else { const text = await response.text(); throw new Error(`Expected JSON, got ${contentType}: ${text}`); } } catch (error) { console.error("Error in postMessage:", error); return { success: false }; } } export async function fetchCourses() { const headers: HeadersInit = { accept: "application/json" }; const url = `${process.env.api_url}course/?skip=0&limit=100`; console.log('Fetching from URL:', url); try { const response = await fetch(url, { headers }); console.log('Response status:', response.status); const result = await response.json(); console.log('Fetched data:', result); const coursesArray: CoursesProps[] = result.data.map((course: CoursesProps) => ({ ...course, images: course.images.sort((a: any, b: any) => a.index - b.index), info_images: course?.info_images?.sort((a: any, b: any) => a.index - b.index), })); return coursesArray; } catch (error) { console.error('Fetch error:', error); throw error; } } export async function fetchCourse(id: string) { const headers: HeadersInit = { accept: "application/json" }; const url = `${process.env.api_url}course/${id}`; console.log('Fetching from URL:', url); try { const response = await fetch(url, { headers }); console.log('Response status:', response.status); var result: CoursesProps = await response.json(); console.log('Fetched data:', result); if (result.info_images && Array.isArray(result.info_images)) { result.info_images.sort((a, b) => a.index - b.index); } return result; } catch (error) { console.error('Fetch error:', error); throw error; } } export async function fetchSettings() { const headers: HeadersInit = { accept: "application/json" }; const url = `${process.env.api_url}setting`; console.log('Fetching from URL:', url); try { const response = await fetch(url, { headers }); console.log('Response status:', response.status); const result: SettingsProps = await response.json(); console.log('Fetched data:', result); return result; } catch (error) { console.error('Fetch error:', error); throw error; } }