const express = require('express');
var bankRouter = 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 validateEntityScopedListQuery = validateListQuery({ requireEntId: true });

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

bankRouter.post('/createbank', chkLogin, aclCheck("create", "Bank"), async (req, res) => {
    try {
        const bank = await new models.Bank().createBank(req.body, req.session.userId);
        if (bank.errors) {
            return res.json(resp("Error", "Error adding Bank data", bank.errors, req, false));
        }

        const entity = await models.Entity.findByPk(req.body.ent_id);
        if (!entity) {
            return res.json(resp("Error", "Entity not found", null, req, false));
        }

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

        await entity.addBank(createdBank);
        return res.json(resp("Bank Created", "Bank added successfully", bank, req));
    } catch (err) {
        return res.json(resp("Error", "Error adding Bank data", err, req, false));
    }
});

bankRouter.post('/readbanks', chkLogin, aclCheck("read", "Bank"), validateEntityScopedListQuery, async (req, res) => {
    new models.Bank().readBanks(req.body.col, req.body.dir, req.body.offset, req.body.limit, req.body.ent_id, req.body.search).then((result) => {
        if(result.errors) {
            return res.json(
                resp(
                    "Error",
                    "Error listing Banks",
                    result.errors,
                    req,
                    false
                )
            )    
        }
        new models.Bank().countBanks(req.body.ent_id).then((count) => {
            return res.json(
                resp(
                    "Bank Data",
                    "List of Banks",
                    {rows: result, rowCount: count},
                    req
                )
            )
        })
    }).catch((err) => {
        return res.json(
            resp(
                "Error",
                "Error listing Banks",
                err,
                req,
                false
            )
        )
    })
});

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

bankRouter.put('/updatebank', chkLogin, aclCheck("update", "Bank"), async (req, res) => {
    new models.Bank().updateBank(req.body).then((result) => {
        return res.json(
            resp(
                "Bank updated",
                "Bank updated successfully",
                result,
                req
            )
        )
    }).catch((err) => {
        return res.json(
            resp(
                "Error",
                "Error updating Bank Data",
                err,
                req
            )
        )
    })
});

bankRouter.delete('/deletebank', chkLogin, aclCheck("delete", "Bank"), async (req, res) => {
    new models.Bank().deleteBank(req.body).then((result) => {
        return res.json(
            resp(
                "Bank Deleted",
                "Bank deleted successfully",
                result,
                req                
            )
        )
    }).catch((err) => {
        return res.json(
            resp(
                "Error",
                "Error deleting Bank Data",
                err,
                req
            )
        )
    })
});

bankRouter.post('/listbanks', chkLogin, aclCheck("read", "Bank"), async (req, res) => {
    new models.Bank().getBanksList(req.body.ent_id).then((result) => {
        if(result.errors) {
            return res.json(
                resp(
                    "Error",
                    "Error listing Banks",
                    result.errors,
                    req,
                    false
                )
            )    
        }
        return res.json(
            resp(
                "Bank Data",
                "List of Banks",
                result,
                req
            )
        )
    }).catch((err) => {
        return res.json(
            resp(
                "Error",
                "Error listing Banks",
                err,
                req,
                false
            )
        )
    })
});

module.exports = bankRouter;