"use client";
import request from "@/lib/request";
import { ApiResponse } from "@/types/types";
import useSWR, { SWRConfiguration } from "swr";
import useSWRMutation, { type SWRMutationConfiguration } from "swr/mutation";

async function fetcher<T>(
	url: string,
	requiresAuth: boolean = true,
	csrfToken?: boolean,
): Promise<ApiResponse<T>> {
	return request(url, { requiresAuth, csrfToken });
}

async function mutationHandler<T, A>(
	url: string,
	{
		arg,
		method,
		requiresAuth,
		csrfToken,
	}: {
		arg: A;
		method: "GET" | "POST" | "PATCH" | "DELETE";
		requiresAuth: boolean;
		csrfToken?: boolean;
	},
): Promise<ApiResponse<T>> {
	return request(url, { method, body: arg, requiresAuth, csrfToken });
}

export function useApi<T>(
	endpoint: string,
	config?: SWRConfiguration,
	requiresAuth: boolean = true,
	csrfToken?: boolean,
) {
	const swr = useSWR<ApiResponse<T>>(
		endpoint,
		() => fetcher(endpoint, requiresAuth, csrfToken),
		config,
	);

	return {
		...swr,
		data: swr.data?.data,
		isLoading: swr.isLoading || swr.isValidating,
		success: swr.data?.status === "Success",
	};
}

export default function useApiMutation<T, A>(
	endpoint: string,
	config?: SWRMutationConfiguration<ApiResponse<T>, Error, string, A>,
	method: "GET" | "POST" | "PATCH" | "DELETE" = "GET",
	requiresAuth: boolean = false,
	csrfToken?: boolean,
) {
	const mutation = useSWRMutation<ApiResponse<T>, Error, string, A>(
		endpoint,
		(url, { arg }) =>
			mutationHandler(url, { arg, method, requiresAuth, csrfToken }),
		config,
	);
	return {
		...mutation,
		trigger: mutation.trigger as (
			arg: A,
		) => Promise<ApiResponse<T> | undefined>,
		data: mutation.data?.data,
		isSuccess: mutation.data?.status === "Success",
	};
}
