import axios from "~/lib/axios";
import { handleError, handleSuccess } from ".";

class AuthApiService {
  async login(credentials: { input: string; password: string }) {
    try {
      const { data } = await axios({
        url: "auth/login",
        data: credentials,
        method: "POST",
        withCredentials: true,
      });

      return data as IResponse<boolean>;
    } catch (error) {
      handleError(error);
    }
  }

  async logout() {
    try {
      const { data } = await axios({
        url: "auth/logout",
        method: "POST",
        withCredentials: true,
      });

      return data as IResponse<boolean>;
    } catch (error) {
      handleError(error);
    }
  }

  async changePassword(credentials: { newPassword: string; password: string }) {
    try {
      const { data } = await axios({
        url: "auth/change-password",
        data: credentials,
        method: "POST",
        withCredentials: true,
      });

      handleSuccess(data);
      return data as IResponse<boolean>;
    } catch (error) {
      handleError(error);
    }
  }

  async me() {
    try {
      const { data } = await axios({
        url: "auth/me",
        method: "GET",
        withCredentials: true,
      });

      return data as IResponse<IUser>;
    } catch (error) {
      handleError(error);
    }
  }
}

export const authApi = new AuthApiService();
