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

export const POST: APIRoute = async({ 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 cookies = request.headers.get("Cookie")?.split(";").map((x) => x.trim().split("=")) ?? [];
    const systemId = cookies.filter((x) => x[0] === "currentSystem")[0]?.[1];

    const userSystem = locationManager.getSystem(new ObjectId(systemId));
    
    if(!userSystem) {
        return new Response(
            JSON.stringify({
                code: 400,
                message: "Bad Request",
                error: "Invalid system ID"
            }), { status: 400 }
        )
    }

    if(userSystem.asteroids.asteroids.length >= 5) {
        return new Response(
            JSON.stringify({
                code: 400,
                message: "Bad Request",
                error: "You have reached the maximum number of asteroids in this system"
            }), { status: 400 }
        )
    }

    const asteroidUUID = new UUID();
    const asteroid: Asteroid = {
        id: asteroidUUID,
        name: `AS-${asteroidUUID}`,
        resources: [
            {
                id: "coal",
                amount: Math.floor(Math.random() * 100) + 1
            }, {
                id: "iron",
                amount: Math.floor(Math.random() * 100) + 1
            }, {
                id: "gold",
                amount: Math.floor(Math.random() * 100) + 1
            }
        ]
    }

    userSystem.asteroids.asteroids.push(asteroid);
    await userSystem.asteroids.sync();

    return new Response(
        JSON.stringify({
            code: 200,
            message: "OK",
            asteroid
        }), { status: 200 }
    );
}