import { MissionLog, prisma } from "@repo/db";
import cron from "node-cron";

const removeClosedMissions = async () => {
	const oldMissions = await prisma.mission.findMany({
		where: {
			state: "running",
		},
	});
	oldMissions.forEach(async (mission) => {
		const lastAlert = (mission.missionLog as unknown as MissionLog[]).find((l) => {
			return l.type === "alert-log";
		});
		const lastAlertTime = lastAlert ? new Date(lastAlert.timeStamp) : null;

		const aircraftsInMission = await prisma.connectedAircraft.findMany({
			where: {
				stationId: {
					in: mission.missionStationIds,
				},
			},
		});

		if (
			!aircraftsInMission ||
			!aircraftsInMission.some((a) => ["1", "2", "6"].includes(a.fmsStatus))
		)
			return;

		const now = new Date();
		if (!lastAlertTime) return;
		// change State to closed if last alert was more than 180 minutes ago
		if (now.getTime() - lastAlertTime.getTime() < 30 * 60 * 1000) return;
		const log: MissionLog = {
			type: "completed-log",
			auto: true,
			timeStamp: new Date().toISOString(),
			data: {},
		};

		await prisma.mission.update({
			where: {
				id: mission.id,
			},
			data: {
				state: "finished",
				missionLog: {
					push: log as any,
				},
			},
		});
		console.log(`Mission ${mission.id} closed due to inactivity.`);
	});
};

cron.schedule("*/5 * * * *", async () => {
	try {
		await removeClosedMissions();
	} catch (error) {
		console.error("Error removing closed missions:", error);
	}
});
