import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react";
import { logout } from "../Redux/Slices/authSlice.js";
import CONFIG from "../Core/сonfig.js";

const baseQuery = fetchBaseQuery({
    baseUrl: CONFIG.BASE_URL,
    prepareHeaders: (headers) => {
        const token = localStorage.getItem("access_token");
        if (token) {
            headers.set("Authorization", `Bearer ${token}`);
        }
        headers.set("Content-Type", "application/json");
        return headers;
    },
});

const baseQueryWithAuth = async (args, api, extraOptions) => {
    const result = await baseQuery(args, api, extraOptions);
    if (result.error && result.error.status === 401) {
        localStorage.removeItem("access_token");
        api.dispatch(logout());
        window.location.href = "/login";
    }
    return result;
};

export const authApi = createApi({
    reducerPath: "authApi",
    baseQuery: baseQueryWithAuth,
    endpoints: (builder) => ({
        login: builder.mutation({
            query: (credentials) => ({
                url: "/login/",
                method: "POST",
                body: credentials,
            }),
        }),
    }),
});

export const { useLoginMutation } = authApi;