import type { IauthenticationData } from "@/contexts/Types";
import { LOG } from "@logger";
import { AxiosError } from "axios";
import axiosRequest from "../axiosRequest";

const log = LOG.extend("authenticateUser");

const authenticateUser = async ({ username, password }: { username: string; password: string }) => {
	log.http({ username, password });
	const response = await axiosRequest<IauthenticationData>({
		url: "/login/token/",
		method: "POST",
		data: {
			username: username,
			password: password,
		},
	});
	log.http(JSON.stringify(response, null, 2));
	return response;
};

export default authenticateUser;

export const parseAuthicationErrors = (error: unknown): string => {
	if (error instanceof AxiosError && error.response) {
		switch (error.response.status) {
			case 401:
				return "Wrong username or password";
			default:
				return "Unknown Error. Please try again.";
		}
	}
	if (error instanceof AxiosError && error.request) {
		return "Network error";
	}
	return "Unknown error";
};
