import axios from "axios";
import { createLogger } from "../logger/logger.controller.js";

type ODToken = {
	odToken: string | null;
	tokenDate: Date | null;
};

export let odToken: ODToken = {
	odToken: null,
	tokenDate: new Date(),
};

export const getToken = async () => {
	const log = createLogger({ module: "opendock", subModule: "auth" });
	try {
		const { status, data } = await axios.post(
			`${process.env.OPENDOCK_URL}/auth/login`,
			{
				email: "blake.matthes@alpla.com",
				password: process.env.OPENDOCK_PASSWORD,
			},
		);

		if (status === 400) {
			log.error(data.message);
			return;
		}

		odToken = { odToken: data.access_token, tokenDate: new Date() };
		log.info({ odToken }, "Token added");
		return;
	} catch (e) {
		log.error({ stack: e }, "Error getting/refreshing token");
	}
};
