import { ObjectId } from 'mongodb';
import DBFleet from '../../types/db/DBFleet';
import { Fleet, Planets, Systems } from '../db/mongodb';

export const getAllFleet = async () => {
    return (await Fleet()).find({}).toArray() as unknown as Array<DBFleet>;
}

export const getAllFleetByUser = async (userId: ObjectId) => {
    const planets = await (await Planets()).find({ owner: userId }).toArray();
    const systems = await (await Systems()).find({ ownedBy: userId }).toArray();

    const fleets = new Map<string, DBFleet>();

    for(const planet of planets) {
        const fleet = await (await Fleet()).find({ $or: [
            { source: planet._id },
            { destination: planet._id }
        ] }).toArray() as unknown as DBFleet[];

        for(const f of fleet) {
            fleets.set(f._id.toString(), f);
        }
    }

    for(const system of systems) {
        const fleet = await (await Fleet()).find({ $or: [
            { source: system._id },
            { destination: system._id }
        ] }).toArray() as unknown as DBFleet[];

        for(const f of fleet) {
            fleets.set(f._id.toString(), f);
        }
    }

    return Array.from(fleets.values());
}

export const createFleet = async (fleet: DBFleet) => {
    return await (await Fleet()).insertOne(fleet);
}

export const updateFleet = async (fleet: DBFleet) => {
    return await (await Fleet()).updateOne({ _id: fleet._id }, { $set: fleet }, { upsert: true });
}