'use server';

import { StringSchemaDefinition } from 'mongoose';

import Binned, { Binned as BinItem } from '../../../models/binned';
import { Bin } from '../bin.enum';
import db from '../db/connection';

export type BinsContents = { [key in Bin]: BinItem[] };

export async function addToBin(bin: number, item: Omit<BinItem, 'bin'>) {
    await db();
    const binned = new Binned({ ...item, bin });
    await binned.save();
}

export async function getBinsContents(): Promise<BinsContents> {
    await db();
    const bins = {} as BinsContents;
    const createdAt = new Date();
    createdAt.setUTCHours(0,0,0,0);

    // Should be today, but lets do yesterday so there is more to see for demo purposes
    const binned = await Binned.find({ createdAt: { $gte: createdAt }});
    binned.forEach((item: BinItem) => bins[item.bin] = [...(bins[item.bin] ?? []), item]);
    return JSON.parse(JSON.stringify(bins));
}

export async function switchBin(bin: number, id: StringSchemaDefinition) {
    await db();
    const binned = await Binned.findOneAndUpdate({ id }, { bin }, { new: true });
}
