import API_URL from "../config/api";
import type { ApiErrorResponse, Workshop } from "../types";

type GetWorkshopsParams = {
    search?: string;
    status?: string;
    page?: number;
    per_page?: number;
};

export function useGetWorkshops() {
    async function getWorkshops(params: GetWorkshopsParams) {
        const query = new URLSearchParams();

        if (params.search) query.append("search", params.search);
        if (params.status) query.append("status", params.status);
        if (params.page) query.append("page", params.page.toString());
        if (params.per_page) query.append("per_page", params.per_page.toString());

        const response = await fetch(`${API_URL}/api/workshops?${query.toString()}`, {
            method: "GET",
            headers: {
                Accept: "application/json",
                "Content-Type": "application/json",
                Authorization: `Bearer ${localStorage.getItem("token")}`
            },
        });

        const data = await response.json();

        if (response.ok) {
            return {
                workshops: data.data as Workshop[],
                meta: data.meta,
                userId: data.userId,
                role: data.role,
            };
        } else {
            return (data as ApiErrorResponse);
        }
    }

    return { getWorkshops };
}