import { RecollectionHistory } from '../models/recollection-history';
import express from 'express';
import passport from 'passport';
import { DB_NAME, getDatabaseClient } from '../db-utils';
import { MongoUser } from '../models/user';
import { ObjectId } from 'bson';

export const recollectionHistoryRoutes = express.Router();

export const jwtAuthentication = passport.authenticate('jwt', { session: false });


// Get recollection history for the user
recollectionHistoryRoutes.get('', jwtAuthentication, async (request, response) => {
    const user: MongoUser = (request.user as any);
    const recollectionHistoryCollection = getDatabaseClient().db(DB_NAME).collection<RecollectionHistory>('recollection-history');

    const recollectionHistoryRecords = await recollectionHistoryCollection.find({
        userId: new ObjectId(user._id)
    }).toArray();

    if (recollectionHistoryRecords.length > 0) {
        response.status(200);
        response.json(recollectionHistoryRecords);
    } else {
        response.status(200);
        response.json([]);
    }

    return;
});


// Add user recollection history
recollectionHistoryRoutes.post('', jwtAuthentication, async (request, response) => {
    const user: MongoUser = (request.user as any);
    const recollectionHistoryCollection = getDatabaseClient().db(DB_NAME).collection<RecollectionHistory>('recollection-history');

    if (!request.body.userId || !request.body.wordId || !request.body.timeStamp || !request.body.wasRecallSuccessful) {
        response.status(400);
        response.send("Missing attributes");
        return;
    }

    const newRecollectionHistoryRecord = await recollectionHistoryCollection.insertOne({
        userId: user._id,
        wordId: request.body.wordId,
        timeStamp: request.body.timeStamp,
        wasRecallSuccessful: request.body.wasRecallSuccessful
    });

    if (newRecollectionHistoryRecord.acknowledged) {
        response.sendStatus(200);
        return;
    } else {
        response.sendStatus(500);
        return;
    }
});