import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react";
import { BaseQueryFn, FetchArgs, FetchBaseQueryError } from "@reduxjs/toolkit/query";
import { logout } from "./authSlice"; // Import logout action from authSlice
import { RootState } from "../Store";

const baseQuery = fetchBaseQuery({
  baseUrl: `${import.meta.env.VITE_API_URL}`,
  prepareHeaders: (headers, { getState }) => {

    const token = (getState() as RootState).auth.token; // Get token from Redux store
    // Encode Basic Auth Credentials
    const username = import.meta.env.VITE_USER_NAME||''; // Replace with actual username
    const password = import.meta.env.VITE_PASSWORD||''; // Replace with actual password
    const basicAuth = `${username} : ${password}`; // Encode to Base64

    if (token) {
      headers.set("Authorization", `Basic ${basicAuth}`);
      headers.set("access-token", `${token}`);
    
    }
    headers.set("Content-Type", "application/json");
    return headers;
  },
});


// ✅ Handle 401 Errors (Auto Logout)
export const baseQueryWithReauth: BaseQueryFn<
  string | FetchArgs,
  unknown,
  FetchBaseQueryError
> = async (args, api, extraOptions) => {
  const result = await baseQuery(args, api, extraOptions);

  if (result.error && result.error.status === 401) {
    api.dispatch(logout()); // Logout user on 401 error
  }

  return result;
};




export const dashboard = createApi({
  reducerPath: "api",
  baseQuery: baseQueryWithReauth, // Use enhanced baseQuery with error handling
  endpoints: (builder) => ({



    getPosts: builder.query<Post[], void>({ query: () => "/posts" }),

    
    // 🔹 POST: Create a new post
    logOut: builder.mutation<void, void>({
      query: () => ({
        url: "/logout",
        method: "POST",
      }),
    }),




  }),
});

export const { useGetPostsQuery, useLogOutMutation } = dashboard;

export type Post = {
  id: number;
  title: string;
  body: string;
};
