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

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

async function getByID(id, include  = {owner: false, preset: false}) {
    return prisma.comment.findUnique({
        where: {
            id: id
        },
        include: include
    }).then((r) => {
        return r
    }).catch((e) => {
        return {error: e.message}
    })
}

async function createForUser(userID, presetID, text) {
    return prisma.comment.create({
        data: {
            text: text,
            owner: {
                connect: {
                    id: userID
                }
            },
            preset: {
                connect: {
                    id: presetID
                }
            }
        },
        include: {
            owner: true
        }
    }).then(async (r) => {
        return r;
    }).catch((e) => {
        return {error: e.message}
    });
}

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

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

async function getByFilter(filter, include = {owner: false, data: false}, max, page) {
    const whereFilter = {};
    if (filter.hasOwnProperty("id") && filter.id !== undefined) {
        whereFilter.id = Number(filter.id);
    }
    if (filter.hasOwnProperty("owner") && filter.owner !== undefined) {
        whereFilter.ownerId = Number(filter.owner);
    }
    if (filter.hasOwnProperty("preset") && filter.preset !== undefined) {
        whereFilter.presetId = Number(filter.preset);
    }

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

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

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