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

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

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

    const planetId = params['planetId'];
    if(!planetId) return new Response(
        JSON.stringify({
            code: 400,
            message: "Bad Request"
        }), { status: 400 }
    );

    const planet = locationManager.getPlanet(new ObjectId(planetId));

    if(!planet) return new Response(
        JSON.stringify({
            code: 500,
            message: "Internal Server Error"
        }), { status: 500 }
    );

    if(!planet.system.data.ownedBy.id.equals(user._id)) return new Response(
        JSON.stringify({
            code: 403,
            message: "Forbidden"
        }), { status: 403 }
    );

    await locationManager.getPlanet(planet._id)?.resources.calculateCurrentAvailableResources();

    return new Response(
        JSON.stringify({
            code: 200,
            message: "OK",
            data: JSON.parse(JSON.stringify(planet).replace(/_id/g, 'id'))
        })
    )
}