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

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 }
        )
    }

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

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

    const structureId: string = body.structureId;

    const structureObj = userSystem.structures.structuresDB.find(s => s.id === structureId);

    if(!structureObj) return new Response(
        JSON.stringify({
            code: 400,
            message: "Bad Request",
            error: "Invalid structure ID"
        }), { status: 400 }
    )

    const structure = new Structure(userSystem.structures, structureObj, 1);

    // const requirements = await structure.checkRequirements();
    // const resources = await building.checkRequiredResources((userPlanet.buildings.getBuildingById(buildingId)?.level ?? 0) + 1);

    // if(!requirements.canBuild || !resources) {
    //     return new Response(
    //         JSON.stringify({
    //             code: 400,
    //             message: "Bad Request",
    //             error: `${requirements.error} | ${resources ? "" : "Not enough resources"}`
    //         }), { status: 400 }
    //     )
    // }

    // const resourcesDiff = await userPlanet.resources.getDifference(building.data.requirements.resources.map(res => {
    //     return {
    //         id: res.id,
    //         amount: Math.pow(building.data.multiplier, (userPlanet.buildings.getBuildingById(buildingId)?.level ?? 0) + 1) * res.amount
    //     }
    // }));

    // const resourceDB = await getAllResources();
    // const resourcesAfter = resourcesDiff.map(res => {
    //     const data = resourceDB.find(r => r.id === res.id);

    //     if(!data) throw new Error("Resource not found");

    //     return {
    //         id: res.id,
    //         amount: res.amount,
    //         lastUpdated: res.lastUpdated,
    //         perHourMiningRate: res.perHourMiningRate,
    //         data
    //     }
    // });

    // userPlanet.resources.update(resourcesAfter);
    // userSystem.structures.addStructure(structure);

    // await userSystem.structures.sync();
    // await userPlanet.resources.sync();

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