import axios from "axios";
import { eq, sql } from "drizzle-orm";
import { Router } from "express";
import { db } from "../db/db.controller.js";
import { opendockApt } from "../db/schema/opendock_apt.schema.js";
import { apiReturn } from "../utils/returnHelper.utils.js";
import { tryCatch } from "../utils/trycatch.utils.js";
import { odToken } from "./opendock.utils.js";

const r = Router();

r.patch("/:id", async (req, res) => {
	//const limit
	const { id } = req.params;

	try {
		const response = await axios.patch(
			`${process.env.OPENDOCK_URL}/appointment/${id}/undo-latest-status`,
			{
				headers: {
					"content-type": "application/json; charset=utf-8",
					Authorization: `Bearer ${odToken.odToken}`,
				},
			},
		);

		if (response.status === 400) {
			return apiReturn(res, {
				success: false,
				level: "error",
				module: "opendock",
				subModule: "apt",
				message: response.data.data.message,
				data: [],
				status: 400,
			});
		}

		// update the release in the db
		const { data } = await tryCatch(
			db
				.update(opendockApt)
				.set({
					appointment: response.data.data,
					upd_date: sql`NOW()`,
				})
				.where(eq(opendockApt.openDockAptId, id)),
		);

		return apiReturn(res, {
			success: true,
			level: "info",
			module: "opendock",
			subModule: "apt",
			message: `The release was reverted to the last state.`,
			data: data as any,
			status: 200,
		});
		// biome-ignore lint/suspicious/noExplicitAny: to many possibilities
	} catch (e: any) {
		return apiReturn(res, {
			success: false,
			level: "error",
			module: "opendock",
			subModule: "apt",
			message: `An error updating the release in opendock`,
			data: e.response.data,
			status: 400,
		});
	}
});

export default r;
