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

export const userProfileRoutes = express.Router();

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

userProfileRoutes.get('/profile/', jwtAuthentication, async (request, response) => {
    const user: MongoUser = (request.user as any);
    response.json({
        _id: user._id,
        name: user.name,
        email: user.email,
        isVerified: user.isVerified,
        categories: user.categories,
        favouriteWords: user.favouriteWords,
    });
    return;
});

// Add favourite word

userProfileRoutes.post('/favourite-words/', jwtAuthentication, async (request, response) => {
    const user: MongoUser = (request.user as any);
    const userCollection = getDatabaseClient().db(DB_NAME).collection<MongoUser>('users');
    const wordCollection = getDatabaseClient().db(DB_NAME).collection<Word>('words');

    if (!user.favouriteWords) {
        user.favouriteWords = [];
    }

    if (!request.body.wordId) {
        response.status(400);
        response.send("Missing wordID");
        return;
    } else if (user.favouriteWords.includes(request.body.wordId)) {
        response.status(400);
        response.send("WordID already present");
        return;
    }

    const matchedWord = await wordCollection.findOne({
        _id: new ObjectId(request.body.wordId)
    });

    if (!matchedWord) {
        response.status(400);
        response.send("Word not present in the library");
        return;
    }

    user.favouriteWords.push(request.body.wordId);

    const updatedUser = await userCollection.updateOne({
        _id: new ObjectId(user._id)
    }, {
        $set: {
            favouriteWords: user.favouriteWords
        }
    });

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

    return;
});

// Update favourite word
userProfileRoutes.put('/favourite-words/', jwtAuthentication, async (request, response) => {
    const user: MongoUser = (request.user as any);
    const userCollection = getDatabaseClient().db(DB_NAME).collection<MongoUser>('users');
    
    if (!request.body.favouriteWords) {
        response.status(400);
        response.send("Missing favouriteWords param");
        return;
    }

    const updatedUser = await userCollection.updateOne({
        _id: new ObjectId(user._id)
    }, {
        $set: {
            favouriteWords: request.body.favouriteWords
        }
    });

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

    return;
});