
import { CoursesProps, CoursesArrayProps, SettingsProps, MessageProps, AboutusProps, OrganProps } 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 = `${process.env.NEXT_PUBLIC_API_URL}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 fetchOrgan() {
    const headers: HeadersInit = {
        accept: "application/json"
    };
    const url = `${process.env.NEXT_PUBLIC_API_URL}organ/`;

    try {
        const response = await fetch(url, { headers });

        const result = await response.json();

        // Sort the result by index
        const sortedResult: OrganProps[] = result.data.sort((a: any, b: any) => a.index - b.index);

        return sortedResult;
    }
    catch (error) {
        console.error('Fetch error:', error);
        throw error;
    }
}

export async function fetchAboutus() {
    const headers: HeadersInit = {
        accept: "application/json"
    };
    const url = `${process.env.NEXT_PUBLIC_API_URL}aboutUs/`;

    try {
        const response = await fetch(url, { headers });

        const result = await response.json();

        // Sort the result by index
        const sortedResult: AboutusProps[] = result.data.sort((a: any, b: any) => a.index - b.index);

        return sortedResult;
    }
    catch (error) {
        console.error('Fetch error:', error);
        throw error;
    }
}



export async function fetchCourses() {
    const headers: HeadersInit = {
        accept: "application/json"
    };

    const url = `${process.env.NEXT_PUBLIC_API_URL}course/?skip=0&limit=100`;
    console.log('Fetching from URL:', url);

    try {
        const response = await fetch(url, { headers, cache: 'no-store', next: { revalidate: 0 } });


        const result = await response.json();


        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),
        }));

        const sortedCoursesArray = coursesArray.sort((a, b) =>
            new Date(a.created_at).getTime() - new Date(a.created_at).getTime()
        );

        return sortedCoursesArray;
    } catch (error) {

        throw error;
    }
}

export async function fetchCourse(id: string) {
    const headers: HeadersInit = {
        accept: "application/json"
    };

    const url = `${process.env.NEXT_PUBLIC_API_URL}course/${id}/`;


    try {
        const response = await fetch(url, {
            headers, cache: 'no-store',
            next: { revalidate: 0 }
        });


        var result: CoursesProps = await response.json();


        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",
        cache: 'no-store'
    };
    const url = `${process.env.NEXT_PUBLIC_API_URL}setting/`;

    try {
        const response = await fetch(url, { headers });

        const result: SettingsProps = await response.json();

        return result;
    }
    catch (error) {
        console.error('Fetch error:', error);
        throw error;
    }
}