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

changeLogRouter.post('/createchangelog', chkLogin, aclCheck("update", "Invoice Management"), async (req, res) => {
    const og_data = await new models.Invoice().readInvoiceRow(req.body.invoice_id);

    new models.ChangeLog().createChangeLog(req.body.invoice_id, req.session.userId, og_data, req.body.new_data).then((result) => {
        if(result.errors) {
            return res.json(
                resp(
                    "Error",
                    "Error adding Change Log data",
                    result.errors,
                    req,
                    false
                )
            )
        }
        new models.Invoice().updateInvoice(req.body.invoice_id, {change_id: result.id}).then((invUpdRes) => {
            if(invUpdRes.errors) {
                return res.json(
                    resp(
                        "Error",
                        "Error updating Invoice data",
                        invUpdRes.errors,
                        req,
                        false
                    )
                )
            }
        }).catch((err) => {
            return res.json(
                resp(
                    "Error",
                    "Error updating Invoice data",
                    err,
                    req
                )
            )
        })
        return res.json(
            resp(
                "Change Log created",
                "Change Log added sucessfully",
                result,
                req
            )
        )
    }).catch((err) => {
        return res.json(
            resp(
                "Error",
                "Error adding Change Log data",
                err,
                req
            )
        )
    })
});

changeLogRouter.post('/readchangelogs', chkLogin, aclCheck("read", "View Invoice"), async (req, res) => {
    const { invoice_id } = req.body;
    if (!invoice_id) {
        return res.status(400).json(resp("Error", "Invoice ID is required", null, req, false));
    }
    new models.ChangeLog().readChangeLogsForInvoice(invoice_id).then((result) => {
        if (result instanceof Error || result?.errors) {
            return res.json(resp("Error", "Error fetching change logs", result.errors || result, req, false));
        }
        return res.json(resp("Change Logs", "Change logs fetched successfully", result, req));
    }).catch((err) => {
        return res.json(resp("Error", "Error fetching change logs", err, req, false));
    });
});

module.exports = changeLogRouter;