import { makeRequest } from "@frontend/kitui";

import { parseAxiosError } from "@root/utils/parse-error";

import type {
  LoginRequest,
  LoginResponse,
  RegisterRequest,
  RegisterResponse,
} from "@frontend/kitui";

const apiUrl = process.env.REACT_APP_DOMAIN + "/auth";

export async function register(
  login: string,
  password: string,
  phoneNumber: string
): Promise<[RegisterResponse | null, string?]> {
  try {
    const registerResponse = await makeRequest<
      RegisterRequest,
      RegisterResponse
    >({
      url: apiUrl + "/register",
      body: { login, password, phoneNumber },
      useToken: false,
      withCredentials: true,
    });

    return [registerResponse];
  } catch (nativeError) {
    const [error] = parseAxiosError(nativeError);

    return [null, `Не удалось зарегестрировать аккаунт. ${error}`];
  }
}

export async function login(
  login: string,
  password: string
): Promise<[LoginResponse | null, string?]> {
  try {
    const loginResponse = await makeRequest<LoginRequest, LoginResponse>({
      url: apiUrl + "/login",
      body: { login, password },
      useToken: false,
      withCredentials: true,
    });

    return [loginResponse];
  } catch (nativeError) {
    const [error] = parseAxiosError(nativeError);

    return [null, `Не удалось войти. ${error}`];
  }
}

export async function recover(
  email: string
): Promise<[unknown | null, string?]> {
  try {
    const formData = new FormData();
    formData.append("email", email);
    formData.append("RedirectionURL", process.env.REACT_APP_DOMAIN + "/changepwd")
    const recoverResponse = await makeRequest<unknown, unknown>({
      url: process.env.REACT_APP_DOMAIN + "/codeword/recover",
      body: formData,
      useToken: false,
      withCredentials: true,
    });
    console.log(recoverResponse)
    return [recoverResponse];
  } catch (nativeError) {
    console.log(nativeError)
    const [error] = parseAxiosError(nativeError);

    return [null, `Не удалось восстановить пароль. ${error}`];
  }
}

export async function logout(): Promise<[unknown, string?]> {
  try {
    const logoutResponse = await makeRequest<never, void>({
      url: apiUrl + "/logout",
      method: "POST",
      useToken: true,
      withCredentials: true,
    });

    return [logoutResponse];
  } catch (nativeError) {
    const [error] = parseAxiosError(nativeError);

    return [null, `Не удалось выйти. ${error}`];
  }
}
