import { APIRoute } from "astro";
import { ObjectId } from "mongodb";
import locationManager from "../../../lib/classes/managers/LocationManager";
import { getUserByAccessToken } from "../../../lib/db/users";
import validateAccessToken from "../../../lib/utils/validateAccessToken";

export const POST: APIRoute = async({ request }) => {
    const response = await validateAccessToken(request);
    if(response instanceof Response) return response;

    const userDB = await getUserByAccessToken(response);
    if(userDB === null) {
        return new Response(
            JSON.stringify({
                code: 401,
                message: "Unauthorized"
            }), { status: 401 }
        )
    }

    const user = locationManager.getUser(userDB._id);
    if(!user) {
        return new Response(
            JSON.stringify({
                code: 401,
                message: "Unauthorized"
            }), { status: 401 }
        )
    }

    let body: { id: string };
    try {
        body = await request.json()
    } catch(e) {
        return new Response(
            JSON.stringify({
                code: 400,
                message: "Bad Request",
                error: "Invalid JSON body"
            }), { status: 400 }
        )
    }

    let id;
    try {
        id = new ObjectId(body.id);
    } catch(e) {
        return new Response(
            JSON.stringify({
                code: 400,
                message: "Bad Request",
                error: "Invalid ID format"
            }), { status: 400 }
        )
    }

    const fleet = locationManager.fleet.find(fleet => fleet.data.id.equals(id));
    if(!fleet) {
        return new Response(
            JSON.stringify({
                code: 404,
                message: "Not Found",
                error: "Fleet not found"
            }), { status: 404 }
        )
    }

    fleet.data.arrivalTime = new Date();
    await fleet.initiateReturn(true);
    await fleet.sync();
    
    return new Response(
        JSON.stringify({
            code: 200,
            message: "OK"
        }), { status: 200 }
    )
}