/**
 * @file usersServices.js
 * @author Radim Buráň (xburan03@stud.fit.vutbr.cz)
 */

const {prisma} = require("./dbService");

async function getByID(id) {
    return prisma.user.findUnique({
        where: {
            id: id
        }
    }).then((r) => {
        return r
    }).catch((e) => {
        return {error: e.message}
    })
}

async function create(data) {
    return prisma.user.create({
        data: data
    }).then((r) => {
        return r;
    }).catch((e) => {
        return {error: e.message}
    });
}

async function update(data) {
    return prisma.user.update({
        where: {
            id: data.id,
        },
        data: data
    }).then((r) => {
        return r;
    }).catch((e) => {
        return {error: e.message}
    });
}

async function deleteByID(id) {
    return prisma.user.delete({
        where: {
            id: id
        }
    }).then((r) => {
        return r;
    }).catch((e) => {
        return {error: e.message}
    });
}

async function getByFilter(filter, max = 20, page = 0) {
    const whereFilter = {};
    if (filter.hasOwnProperty("id") && filter.id !== undefined) {
        whereFilter.id = Number(filter.id);
    }
    if (filter.hasOwnProperty("email") && filter.email !== undefined) {
        whereFilter.email = filter.email;
    }
    if (filter.hasOwnProperty("name") && filter.name !== undefined) {
        whereFilter.name = filter.name;
    }
    if (filter.hasOwnProperty("role") && filter.role !== undefined) {
        whereFilter.role = filter.role;
    }

    const count = await prisma.user.count({
        where: whereFilter
    });

    return prisma.user.findMany({
        where: whereFilter,
        take: max,
        skip: max * page
    }).then((r) => {
        return {
            count: count,
            items: r
        };
    }).catch((e) => {
        return {error: e.message}
    });
}

module.exports = {
    getByID,
    create,
    update,
    deleteByID,
    getByFilter
}