const { ObjectId } = require('mongodb');
const connectDb = require("./db");
const crypto = require('crypto');

const UserDb = class
{
    constructor()
    {
    }

    static async init() {
        const userDb = new UserDb();
        await userDb.getCollection();
        return userDb;
    }

    async getCollection()
    {
        const db = await connectDb();
        if (!db) {
            throw new Error('Database not connected');
        }
        this.collection = db.collection("Users");
    }

    // CRUD
    async get(id)
    {
        let result = await this.collection.findOne({_id: new ObjectId(id)});
        return result;
    }

    async post(newDocument)
    {
        delete newDocument._id;
        let result = await this.collection.insertOne(newDocument);
        return result;
    }

    async put(id, data)
    {        
        delete data._id;
        let result = await this.collection.updateOne({_id: new ObjectId(id)}, {$set: data});
        return result;
    }

    async remove(id)
    {
        let result = await this.collection.deleteOne({_id: new ObjectId(id)});   
        return result;
    }

    // Functions

    async getAll()
    {
        let result = await this.collection.find({}).toArray();
        return result;
    }

    async getByUsername(username)
    {
        let result = await this.collection.findOne({username: username});
        return result;
    }
    async getByEmail(email)
    {
        let result = await this.collection.findOne({email: email});
        return result;
    }

    async creatFirstUserifEmpty( ){
        const allUsers = await this.getAll();
        if(allUsers.length == 0){
            console.log("Creating first user");
            let salt = crypto.randomBytes(16).toString('hex');
            let user = {                
                username: "admin",
                hashed_password: crypto.pbkdf2Sync('admin', salt, 310000, 32, 'sha256').toString('hex'),
                salt: salt,
                email: "admin@admin.com",                
                isAdmin: true,
                isAgent: false,

            }
            this.post(user);
        }
    }
}

module.exports = { UserDb };