import { APIRoute } from "astro";
import parseParams from "../../../lib/utils/parseParams";
import locationManager, { Sector } from "../../../lib/classes/managers/LocationManager";
import SystemManager from "../../../lib/classes/managers/SystemManager";
import { Planet } from "../../../lib/classes/managers/PlanetManager";
import getDistanceBetween from "../../../lib/utils/getDistanceBetween";

export const GET: APIRoute = async({ request }) => {
    const URLParams = parseParams(request.url);
    if(!URLParams.source || !URLParams.destination) {
        return new Response(
            JSON.stringify({
                code: 400,
                message: "Bad Request",
                error: "Missing parameters"
            }), { status: 400 }
        );
    }

    const source = locationManager.findId(URLParams.source);
    if(source === null) {
        return new Response(
            JSON.stringify({
                code: 404,
                message: "Not Found",
                error: "Source not found"
            }), { status: 404 }
        );
    }

    let destination: Planet | SystemManager | Sector | null = locationManager.findId(URLParams.destination);
    if(destination === null) destination = locationManager.getSector(URLParams.destination) ?? null;
    if(destination === null) {
        return new Response(
            JSON.stringify({
                code: 404,
                message: "Not Found",
                error: "Destination not found"
            }), { status: 404 }
        );
    }

    return new Response(
        JSON.stringify({
            code: 200,
            message: "OK",
            distance: getDistanceBetween(source, destination)
        }), { status: 200 }
    )
}