const { Model, DataTypes } = require('sequelize');
const sequelize = require('../config/db.js');

class ChangeLog extends Model {
    static associate(models) {
        ChangeLog.belongsTo(models.Invoice, {
            as: "invoice",
            foreignKey: "invoice_id",
        });

        ChangeLog.belongsTo(models.User, {
            as: "user",
            foreignKey: "user_id",
        });
    }

    async createChangeLog(invoice_id, user_id, og_data, new_data) {
        try {
            const changeLog = await ChangeLog.create({invoice_id, user_id, og_data, new_data});
            console.log(changeLog.toJSON());
            return changeLog.toJSON();
        } catch (err) {
            console.log(err);
            return err;
        }
    }

    async readChangeLogs() {
        try {
            const changeLogs = await ChangeLog.findAll();
            return changeLogs;
        } catch (err) {
            console.log(err);
            return err;
        }
    }

    async readChangeLogRow(id) {
        try {
            const changeLog = await ChangeLog.findOne(
                {
                    where: {
                        id: id,
                    },
                }
            );
            return changeLog;
        } catch (err) {
            console.log(err);
            return err;
        }
    }

    async readChangeLogsForInvoice(invoice_id) {
        try {
            const changeLogs = await ChangeLog.findAll({
                where: { invoice_id },
                order: [['createdAt', 'DESC']],
            });
            return changeLogs.map(c => c.toJSON());
        } catch (err) {
            console.log(err);
            return err;
        }
    }
}

ChangeLog.init(
    {
        invoice_id: {
            type: DataTypes.INTEGER,
            allowNull: false,
        },
        og_data: {
            type: DataTypes.JSON,
            allowNull: false,
        },
        new_data: {
            type: DataTypes.JSON,
            allowNull: false,
        },
        user_id: {
            type: DataTypes.INTEGER,
            allowNull: false,
        },
    },
    {
        sequelize,
        modelName: 'ChangeLog',
        tableName: 'change_logs',
    }
);

module.exports = ChangeLog;