
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 Year_end_operationsDBApi {
    

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

        const year_end_operations = await db.year_end_operations.create(
            {
                id: data.id || undefined,
        
        operation_type: data.operation_type
        ||
        null
            ,
            
        operation_date: data.operation_date
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await year_end_operations.setBusiness( data.business || null, {
            transaction,
        });
        
        await year_end_operations.setFiscal_year( data.fiscal_year || null, {
            transaction,
        });
        
        await year_end_operations.setGenerated_voucher( data.generated_voucher || null, {
            transaction,
        });
        

        

        

        return year_end_operations;
    }
    

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

        // Prepare data - wrapping individual data transformations in a map() method
        const year_end_operationsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                operation_type: item.operation_type
            ||
            null
            ,
            
                operation_date: item.operation_date
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                notes: item.notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

        // Bulk create items
        const year_end_operations = await db.year_end_operations.bulkCreate(year_end_operationsData, { transaction });

        // For each item created, replace relation files
        

        return year_end_operations;
    }

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

        const year_end_operations = await db.year_end_operations.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.operation_type !== undefined) updatePayload.operation_type = data.operation_type;
        
        
        if (data.operation_date !== undefined) updatePayload.operation_date = data.operation_date;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.business !== undefined) {
            await year_end_operations.setBusiness(
              
              data.business,
              
              { transaction }
            );
        }
        
        if (data.fiscal_year !== undefined) {
            await year_end_operations.setFiscal_year(
              
              data.fiscal_year,
              
              { transaction }
            );
        }
        
        if (data.generated_voucher !== undefined) {
            await year_end_operations.setGenerated_voucher(
              
              data.generated_voucher,
              
              { transaction }
            );
        }
        

        
        

        

        return year_end_operations;
    }

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

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

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


        return year_end_operations;
    }

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

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

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

        await year_end_operations.destroy({
            transaction
        });

        return year_end_operations;
    }

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

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

        if (!year_end_operations) {
            return year_end_operations;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.business = await year_end_operations.getBusiness({
            transaction
        });
        
        
        output.fiscal_year = await year_end_operations.getFiscal_year({
            transaction
        });
        
        
        output.generated_voucher = await year_end_operations.getGenerated_voucher({
            transaction
        });
        
        

        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 orderBy = null;

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

    let include = [

      {
        model: db.businesses,
        as: 'business',
        
        where: filter.business ? {
          [Op.or]: [
            { id: { [Op.in]: filter.business.split('|').map(term => Utils.uuid(term)) } },
            {
              trade_name: {
                [Op.or]: filter.business.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.fiscal_years,
        as: 'fiscal_year',
        
        where: filter.fiscal_year ? {
          [Op.or]: [
            { id: { [Op.in]: filter.fiscal_year.split('|').map(term => Utils.uuid(term)) } },
            {
              title: {
                [Op.or]: filter.fiscal_year.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.journal_vouchers,
        as: 'generated_voucher',
        
        where: filter.generated_voucher ? {
          [Op.or]: [
            { id: { [Op.in]: filter.generated_voucher.split('|').map(term => Utils.uuid(term)) } },
            {
              voucher_number: {
                [Op.or]: filter.generated_voucher.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

        if (filter) {
            if (filter.id) {
                where = {
                    ...where,
                    ['id']: Utils.uuid(filter.id),
                };
            }

            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'year_end_operations',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

            
            if (filter.operation_dateRange) {
                const [start, end] = filter.operation_dateRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                    operation_date: {
                    ...where.operation_date,
                            [Op.gte]: start,
                    },
                };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    operation_date: {
                    ...where.operation_date,
                            [Op.lte]: end,
                    },
                };
                }
            }
            

            if (filter.active !== undefined) {
                where = {
                    ...where,
                    active: filter.active === true || filter.active === 'true'
                };
            }

            
            if (filter.operation_type) {
                where = {
                    ...where,
                operation_type: filter.operation_type,
            };
            }
            
            if (filter.status) {
                where = {
                    ...where,
                status: filter.status,
            };
            }
            


      

      

      



            if (filter.createdAtRange) {
                const [start, end] = filter.createdAtRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                        ['createdAt']: {
                            ...where.createdAt,
                            [Op.gte]: start,
                        },
                    };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                        ['createdAt']: {
                            ...where.createdAt,
                            [Op.lte]: end,
                        },
                    };
                }
            }
        }
        

        

        const queryOptions = {
            where,
            include,
            distinct: true,
            order: filter.field && filter.sort
                ? [[filter.field, filter.sort]]
                : [['createdAt', 'desc']],
            transaction: options?.transaction,
            logging: console.log
        };

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

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

            return {
                rows: 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(
                        'year_end_operations',
                        'operation_type',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

