const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');

const Sequelize = db.Sequelize;
const Op = Sequelize.Op;

module.exports = class Workers_comp_classesDBApi {
    static async create(data, options) {
        const currentUser = (options && options.currentUser) || { id: null };
        const transaction = (options && options.transaction) || undefined;

        const workers_comp_classes = await db.workers_comp_classes.create(
            {
                id: data.id || undefined,
                name: data.name || null,
                percentage: data.percentage !== undefined ? data.percentage : null,
                importHash: data.importHash || null,
                createdById: currentUser.id,
                updatedById: currentUser.id,
            },
            { transaction },
        );

        return workers_comp_classes;
    }
    
    static async update(id, data, options) {
        const currentUser = (options && options.currentUser) || {id: null};
        const transaction = (options && options.transaction) || undefined;
        
        const workers_comp_classes = await db.workers_comp_classes.findByPk(id, {}, {transaction});

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        if (data.percentage !== undefined) updatePayload.percentage = data.percentage === "" ? null : data.percentage;
        
        updatePayload.updatedById = currentUser.id;

        await workers_comp_classes.update(updatePayload, {transaction});

        return workers_comp_classes;
    }

    static async deleteByIds(ids, options) {
        const currentUser = (options && options.currentUser) || { id: null };
        const transaction = (options && options.transaction) || undefined;

        const workers_comp_classes = await db.workers_comp_classes.findAll({
            where: {
                id: {
                    [Op.in]: ids,
                },
            },
            transaction,
        });

        await db.sequelize.transaction(async (transaction) => {
            for (const record of workers_comp_classes) {
                await record.update(
                    {deletedBy: currentUser.id},
                    {transaction}
                );
            }
            for (const record of workers_comp_classes) {
                await record.destroy({transaction});
            }
        });

        return workers_comp_classes;
    }

    static async remove(id, options) {
        const currentUser = (options && options.currentUser) || {id: null};
        const transaction = (options && options.transaction) || undefined;

        const workers_comp_classes = await db.workers_comp_classes.findByPk(id, options);

        await workers_comp_classes.update({
            deletedBy: currentUser.id
        }, {
            transaction,
        });

        await workers_comp_classes.destroy({
            transaction
        });

        return workers_comp_classes;
    }

    static async findBy(where, options) {
        const transaction = (options && options.transaction) || undefined;

        const workers_comp_classes = await db.workers_comp_classes.findOne(
            { where },
            { transaction },
        );

        if (!workers_comp_classes) {
            return workers_comp_classes;
        }

        const output = workers_comp_classes.get({plain: true});

        return output;
    }

    static async findAll(filter, options) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        offset = currentPage * limit;

        const transaction = (options && options.transaction) || undefined;

        let include = [];

        if (filter) {
            if (filter.id) {
                where = { ...where, ['id']: Utils.uuid(filter.id) };
            }
            if (filter.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike('workers_comp_classes', 'name', filter.name),
                };
            }
        }
        
        const queryOptions = {
            where,
            include,
            distinct: true,
            order: filter && filter.field && filter.sort
                ? [[filter.field, filter.sort]]
                : [['createdAt', 'desc']],
            transaction: options && options.transaction,
        };

        if (!(options && options.countOnly)) {
            queryOptions.limit = limit ? Number(limit) : undefined;
            queryOptions.offset = offset ? Number(offset) : undefined;
        }

        try {
            const { rows, count } = await db.workers_comp_classes.findAndCountAll(queryOptions);

            return {
                rows: (options && options.countOnly) ? [] : rows,
                count: count
            };
        } catch (error) {
            console.error('Error executing query:', error);
            throw error;
        }
    }

    static async findAllAutocomplete(query, limit, offset) {
        let where = {};
        
        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike('workers_comp_classes', 'name', query),
                ],
            };
        }

        const records = await db.workers_comp_classes.findAll({
            attributes: [ 'id', 'name' ],
            where,
            limit: limit ? Number(limit) : undefined,
            offset: offset ? Number(offset) : undefined,
            order: [['name', 'ASC']],
        });

        return records.map((record) => ({
            id: record.id,
            label: record.name,
        }));
    }
};