import { baseApi } from "./baseApi";
import { API_ENDPOINTS } from "./constant";
import { logout as logoutAction } from "@/redux/slices/authSlice";
import { clearAuthTokens } from "@/lib/auth-cookies";
import { IAPISuccesResponse } from "./types/common";
import {
  ISignupRequest,
  ISignupResponseData,
  IVerifyEmailRequest,
  IResendOtpRequest,
  ISigninRequest,
  ISigninResponseData,
  IGetProfileResponse,
  IUpdateProfileRequest,
  IUploadAttachmentResponse,
  IForgotPasswordRequest,
  IForgotPasswordResponse,
  IResetPasswordRequest,
  IFollowerItem,
  IFollowingItem,
  IFollowListResponse,
  IExploreUser,
  IUpdateBillingRegionRequest,
} from "./types/auth";

interface IFollowListParams {
  id: string | number;
  page?: number;
  perPage?: number;
  searchText?: string;
}

export const authApi = baseApi.injectEndpoints({
  endpoints: (builder) => ({
    signup: builder.mutation<ISignupResponseData, ISignupRequest>({
      query: (userData) => ({
        url: API_ENDPOINTS.signup,
        method: "POST",
        body: userData,
      }),
    }),
    verifyEmail: builder.mutation<ISigninResponseData, IVerifyEmailRequest>({
      query: (verifyData) => ({
        url: API_ENDPOINTS.verifyEmail,
        method: "POST",
        body: verifyData,
      }),
    }),
    resendOtp: builder.mutation<any, IResendOtpRequest>({
      query: (resendData) => ({
        url: API_ENDPOINTS.resendOtp,
        method: "POST",
        body: resendData,
      }),
    }),
    signin: builder.mutation<ISigninResponseData, ISigninRequest>({
      query: (userData) => ({
        url: API_ENDPOINTS.signin,
        method: "POST",
        body: userData,
      }),
    }),
    logout: builder.mutation<null, void>({
      queryFn: (_, { dispatch }) => {
        clearAuthTokens();
        dispatch(logoutAction());
        dispatch(baseApi.util.resetApiState());
        return { data: null };
      },
    }),
    getProfile: builder.query<IGetProfileResponse, string | number>({
      query: (id) => ({
        url: `/user/${id}/profile`,
        method: "GET",
      }),
      providesTags: ["User"],
    }),
    getCurrentUser: builder.query<IGetProfileResponse, void>({
      query: () => ({
        url: API_ENDPOINTS.profile,
        method: "GET",
      }),
      providesTags: ["User"],
    }),
    updateProfile: builder.mutation<any, IUpdateProfileRequest>({
      query: (data) => ({
        url: API_ENDPOINTS.updateProfile,
        method: "PATCH",
        body: data,
      }),
    }),
    updateBillingRegion: builder.mutation<unknown, IUpdateBillingRegionRequest>({
      query: (data) => ({
        url: API_ENDPOINTS.billingRegion,
        method: "PATCH",
        body: data,
      }),
      // Refresh the profile (region) and the plan list (region-specific prices).
      invalidatesTags: ["User", "Plan"],
    }),
    uploadAttachment: builder.mutation<IUploadAttachmentResponse, FormData>({
      query: (formData) => ({
        url: API_ENDPOINTS.attachment,
        method: "POST",
        body: formData,
      }),
    }),
    forgotPassword: builder.mutation<
      IAPISuccesResponse<IForgotPasswordResponse>,
      IForgotPasswordRequest
    >({
      query: (data) => ({
        url: API_ENDPOINTS.forgotPassword,
        method: "POST",
        body: data,
      }),
    }),
    resetPassword: builder.mutation<IAPISuccesResponse<any>, IResetPasswordRequest>({
      query: (data) => ({
        url: API_ENDPOINTS.resetPassword,
        method: "POST",
        body: data,
      }),
    }),
    updatePassword: builder.mutation<
      IAPISuccesResponse<void>,
      {
        currentPassword: string;
        newPassword: string;
        confirmNewPassword: string;
      }
    >({
      query: (data) => ({
        url: API_ENDPOINTS.updatePassword,
        method: "POST",
        body: data,
      }),
    }),
    followUser: builder.mutation<unknown, number>({
      query: (userId) => ({
        url: `/user/${userId}/follow`,
        method: "POST",
      }),
      invalidatesTags: ['QuestionDetail', 'FollowList'],
    }),
    getFollowers: builder.query<IFollowListResponse<IFollowerItem>, IFollowListParams>({
      query: ({ id, page = 1, perPage = 20, searchText }) => ({
        url: `/user/${id}/followers`,
        method: "GET",
        params: {
          page,
          perPage,
          sortBy: "id",
          sortDirection: "desc",
          ...(searchText ? { searchText } : {}),
        },
      }),
      providesTags: ['FollowList'],
    }),
    getFollowing: builder.query<IFollowListResponse<IFollowingItem>, IFollowListParams>({
      query: ({ id, page = 1, perPage = 20, searchText }) => ({
        url: `/user/${id}/following`,
        method: "GET",
        params: {
          page,
          perPage,
          sortBy: "id",
          sortDirection: "desc",
          ...(searchText ? { searchText } : {}),
        },
      }),
      providesTags: ['FollowList'],
    }),
    getExploreUsers: builder.query<
      IFollowListResponse<IExploreUser>,
      { page?: number; perPage?: number; searchText?: string }
    >({
      query: ({ page = 1, perPage = 20, searchText }) => ({
        url: API_ENDPOINTS.publicUserList,
        method: "GET",
        params: {
          page,
          perPage,
          sortBy: "id",
          sortDirection: "desc",
          higherOrEqualRank: true,
          ...(searchText ? { searchText } : {}),
        },
      }),
      providesTags: ['FollowList'],
    }),
  }),
});

export const {
  useSignupMutation,
  useVerifyEmailMutation,
  useResendOtpMutation,
  useSigninMutation,
  useLogoutMutation,
  useGetProfileQuery,
  useLazyGetProfileQuery,
  useGetCurrentUserQuery,
  useLazyGetCurrentUserQuery,
  useUpdateProfileMutation,
  useUpdateBillingRegionMutation,
  useUploadAttachmentMutation,
  useForgotPasswordMutation,
  useResetPasswordMutation,
  useUpdatePasswordMutation,
  useFollowUserMutation,
  useGetFollowersQuery,
  useGetFollowingQuery,
  useGetExploreUsersQuery,
} = authApi;
