import { apiSlice } from "../../api/auth";
import { setCredentials } from "./authSlice";
import { APIResponse } from "../../../types/api";
import { UserResponse, LoginProps } from "./type";

const login = apiSlice.injectEndpoints({
  endpoints: (builder) => ({
    login: builder.mutation<UserResponse, LoginProps>({
      query: (credentials) => ({
        url: "/auth/login/",
        method: "POST",
        body: { ...credentials },
      }),

      transformResponse(response: APIResponse<UserResponse>) {
        return response.data;
      },
      async onQueryStarted(_, { dispatch, queryFulfilled }) {
        try {
          const { data } = await queryFulfilled;
          dispatch(setCredentials(data));
        } catch (err) {
          console.log(err);
        }
      },
    }),
  }),
});

export const { useLoginMutation } = login;
