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

export const recollectionHistoryRoutes = express.Router();

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


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

    let queryParams: {
        userId: string,
        wordId?: string
    } = {
        userId: user._id,
    };

    if (request.body.wordId) {
        queryParams = {
            userId: user._id,
            wordId: request.body.wordId
        };
    }

    const recollectionHistoryRecords = await recollectionHistoryCollection.find(queryParams).toArray();

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

    return;
});