import axios from "axios";
import { and, desc, eq, gte, 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.get("/", async (req, res) => {
	//const limit

	const daysCreated = req.query.daysCreated ?? 30;

	const { data } = await tryCatch(
		db
			.select()
			.from(opendockApt)
			.where(
				and(
					gte(
						opendockApt.upd_date,
						sql.raw(`NOW() - INTERVAL '${daysCreated} days'`),
					),
					eq(opendockApt.status, "active"),
				),
			)
			.orderBy(desc(opendockApt.upd_date))
			.limit(500),
	);

	apiReturn(res, {
		success: true,
		level: "info",
		module: "opendock",
		subModule: "apt",
		message: `The first ${data?.length} Apt(s) that were created in the last ${daysCreated} `,
		data: data ?? [],
		status: 200,
	});
});

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

	const { data: releaseInfo } = (await tryCatch(
		db
			.select()
			.from(opendockApt)
			.where(eq(opendockApt.id, id as string)),
	)) as any;

	if (releaseInfo.length === 0) {
		return apiReturn(res, {
			success: false,
			level: "error",
			module: "opendock",
			subModule: "apt",
			message: "Invalid release id passed over please try again",
			data: [],
			status: 400,
		});
	}

	try {
		const response = await axios.delete(
			`${process.env.OPENDOCK_URL}/appointment/${releaseInfo[0].appointment.id}`,
			{
				headers: {
					"content-type": "application/json; charset=utf-8",
					Authorization: `Bearer ${odToken.odToken}`,
				},
			},
			// {
			// 	hardDelete: true,
			// },
		);

		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 leaving as insert just in-case something weird happened
		const { data } = await tryCatch(
			db
				.delete(opendockApt)
				.where(eq(opendockApt.id, id as string))
				.returning(),
		);

		return apiReturn(res, {
			success: true,
			level: "info",
			module: "opendock",
			subModule: "apt",
			message: `The release was deleted, this is un unrecoverable`,
			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 deleting the release in opendock`,
			data: e.response.data,
			status: 400,
		});
	}
});

export default r;
