import {TokenError, TokenSuccess} from "@/interfaces/paypal";
import {base64} from "@firebase/util";
import axios from "axios";

export const getAccessToken = async () => {
	const params = new URLSearchParams();
	params.append("grant_type", "client_credentials");

	const auth = base64.encodeString(`${process.env.PAYPAL_CLIENT_ID}:${process.env.PAYPAL_CLIENT_SECRET}`);

	const request = await axios
		.post<TokenSuccess>(`${process.env.PAYPAL_ACCESS_TOKEN_URL}/v1/oauth2/token`, params, {
			headers: {Authorization: `Basic ${auth}`},
		})
		.catch((e) => {
			console.log(e);
			return undefined;
		});

	if (!request) {
		return undefined;
	}

	return request.data.access_token;
};
