import { Course, CourseAttendeeRole, CourseEventDetails, CourseEventSummary } from '@shared/types/course'

//@ts-ignore
const addr = import.meta.env.VITE_APIHOST;

export async function getTrainingReports(sortMode: string, search: string): Promise<CourseEventSummary[]> {
    const res = await fetch(`${addr}/courseEvent?sort=${sortMode}&search=${search}`, {
        credentials: 'include',
    });

    if (res.ok) {
        return await res.json() as Promise<CourseEventSummary[]>;
    } else {
        console.error("Something went wrong");
        throw new Error("Failed to load training reports");
    }
}

export async function getTrainingReport(id: number): Promise<CourseEventDetails> {
    const res = await fetch(`${addr}/courseEvent/${id}`, {
        credentials: 'include',
    });

    if (res.ok) {
        return await res.json() as Promise<CourseEventDetails>;
    } else {
        console.error("Something went wrong");
        throw new Error("Failed to load training reports");
    }
}

export async function getAllTrainings(): Promise<Course[]> {
    const res = await fetch(`${addr}/course`, {
            credentials: 'include',
    });

    if (res.ok) {
        return await res.json() as Promise<Course[]>;
    } else {
        console.error("Something went wrong");
        throw new Error("Failed to load training list");
    }
}

export async function getAllAttendeeRoles(): Promise<CourseAttendeeRole[]> {
    const res = await fetch(`${addr}/course/roles`, {
        credentials: 'include',
    });

    if (res.ok) {
        return await res.json() as Promise<CourseAttendeeRole[]>;
    } else {
        console.error("Something went wrong");
        throw new Error("Failed to load attendee roles");
    }
}

export async function postTrainingReport(report: CourseEventDetails) {
    const res = await fetch(`${addr}/courseEvent`, {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
        },
        body: JSON.stringify(report),
        credentials: 'include',
    });

    if (!res.ok) {
        const errorText = await res.text();
        throw new Error(`Failed to post training report: ${res.status} ${errorText}`);
    }

    return res.json(); // expected to return the inserted report or new ID
}
