const express = require('express');
var entityRouter = express.Router();
const models = require('../models/index.js');
const chkLogin = require('../middleware/auth.js');
const aclCheck = require('../middleware/aclCheck.js');
const requireUserGroup = require('../middleware/requireUserGroup.js');
const validateListQuery = require('../middleware/validateListQuery.js');
var resp = require('../response.js');

const validateStandardListQuery = validateListQuery();

entityRouter.use(chkLogin, requireUserGroup('User'));

entityRouter.post('/createentity', chkLogin, aclCheck("create", "Entity"), async (req, res) => {
    try {
        const entity = await new models.Entity().createEntity(req.body, req.session.userId);
        if (entity.errors) {
            return res.json(resp("Error", "Error adding Entity data", entity.errors, req, false));
        }

        const user = await models.User.findByPk(req.session.userId);
        if (!user) {
            return res.json(resp("Error", "User not found", null, req, false));
        }

        const createdEntity = await models.Entity.findByPk(entity.id);
        if (!createdEntity) {
            return res.json(resp("Error", "Entity creation failed", null, req, false));
        }

        await user.addEntity(createdEntity);
        return res.json(resp("Entity created", "Entity added successfully", entity, req));
    } catch (err) {
        return res.json(resp("Error", "Error adding Entity data", err, req, false));
    }
});

entityRouter.post('/readentities', chkLogin, aclCheck("read", "Entity"), validateStandardListQuery, async (req, res) => {
    var id = req.session.userId;
    new models.Entity().readEntity(req.body.col, req.body.dir, req.body.offset, req.body.limit, id, req.body.search).then((result) => {
        if(result.errors) {
            return res.json(
                resp(
                    "Error",
                    "Error listing Banks",
                    result.errors,
                    req,
                    false
                )
            )    
        }
        new models.Entity().countEntity(id).then((count) => {
            return res.json(
                resp(
                    "Entity Data",
                    "List of Entities",
                    {rows: result, rowCount: count},
                    req
                )
            )
        })
    }).catch((err) => {
        return res.json(
            resp(
                "Error",
                "Error listing Entity",
                err,
                req,
                false
            )
        )
    })
});

entityRouter.post('/readentityrow', chkLogin, aclCheck("read", "Entity"), async (req, res) => {
    new models.Entity().readEntityRow(req.body).then((result) => {
        if(result.errors) {
            return res.json(
                resp(
                    "Error",
                    `Error finding Entity with ID ${req.body.id}`,
                    err,
                    req,
                    false
                )
            )
        }
        return res.json(
            resp(
                "Entity Row Data",
                `Entity with ID ${req.body.id}`,
                result,
                req
            )
        )
    }).catch((err) => {
        return res.json(
            resp(
                "Error",
                `Error finding Entity with ID ${req.body.id}`,
                err,
                req,
                false
            )
        )
    })
});

entityRouter.put('/updateentity', chkLogin, aclCheck("update", "Entity"), async (req, res) => {
    new models.Entity().updateEntity(req.body).then((result) => {
        if(result.errors || result == 0) {
            return res.json(
                resp(
                    "Error",
                    "Error updating Entity data",
                    result.errors,
                    req,
                    false
                )
            )
        }
        return res.json(
            resp(
                "Entity updated",
                "Entity updated successfully",
                result,
                req
            )
        )
    }).catch((err) => {
        return res.json(
            resp(
                "Error",
                "Error updating Entity data",
                err,
                req,
                false
            )
        )
    })
});

entityRouter.delete('/deleteentity', chkLogin, aclCheck("delete", "Entity"), async (req, res) => {
    new models.Entity().deleteEntity(req.body).then((result) => {
        return res.json(
            resp(
                "Entity Deleted",
                "Entity deleted successfully",
                result,
                req
            )
        )
    }).catch((err) => {
        return res.json(
            resp(
                "Error",
                "Error deleting Entity data",
                err,
                req
            )
        )
    })
});

module.exports = entityRouter;