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

type GetVideosParams = {
    page?: number;
    search?: string;
    category?: string;
    status?: "active" | "inactive";
    watched?: 0 | 1;
};

export function useGetVideos() {
    async function getVideos(params: GetVideosParams) {
        const query = new URLSearchParams();

        if (params.page !== undefined) query.append("page", params.page.toString());
        if (params.search) query.append("search", params.search);
        if (params.category) query.append("category", params.category);
        if (params.status) query.append("status", params.status);
        if (params.watched !== undefined) query.append("watched", params.watched.toString());

        const response = await fetch(`${API_URL}/api/videos?${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 {
                videos: data.data as Video[],
                meta: data.meta,
                role: data.role,
                categories: data.categories as Category[],
                videosActive: data.videosActive,
                videosWatched: data.videosWatched,
            };
        } else {
            return data as ApiErrorResponse;
        }
    }

    return { getVideos };
}