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: "https://api.example.com",
  prepareHeaders: (headers, { getState }) => {
    const token = (getState() as RootState).auth.token; // Get token from Redux store
    if (token) {
      headers.set("Authorization", `Bearer ${token}`);
    }
    headers.set("Content-Type", "application/json");
    return headers;
  },
});

// ✅ Handle 401 Errors (Auto Logout)
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 apiSlice = createApi({
  reducerPath: "api",
  baseQuery: baseQueryWithReauth, // Use enhanced baseQuery with error handling
  endpoints: (builder) => ({



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




    
  }),
});

export const { useGetPostsQuery } = apiSlice;

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