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

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

        const journal_vouchers = await db.journal_vouchers.create(
            {
                id: data.id || undefined,
        
        voucher_number: data.voucher_number
        ||
        null
            ,
            
        voucher_date: data.voucher_date
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
        total_debit: data.total_debit
        ||
        null
            ,
            
        total_credit: data.total_credit
        ||
        null
            ,
            
        is_balanced: data.is_balanced
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await journal_vouchers.setBusiness( data.business || null, {
            transaction,
        });
        
        await journal_vouchers.setFiscal_year( data.fiscal_year || null, {
            transaction,
        });
        
        await journal_vouchers.setBranch( data.branch || null, {
            transaction,
        });
        
        await journal_vouchers.setVoucher_type( data.voucher_type || null, {
            transaction,
        });
        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.journal_vouchers.getTableName(),
                belongsToColumn: 'attachments',
                belongsToId: journal_vouchers.id,
            },
            data.attachments,
            options,
        );
        

        return journal_vouchers;
    }
    

    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 journal_vouchersData = data.map((item, index) => ({
                id: item.id || undefined,
                
                voucher_number: item.voucher_number
            ||
            null
            ,
            
                voucher_date: item.voucher_date
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                description: item.description
            ||
            null
            ,
            
                total_debit: item.total_debit
            ||
            null
            ,
            
                total_credit: item.total_credit
            ||
            null
            ,
            
                is_balanced: item.is_balanced
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        
        for (let i = 0; i < journal_vouchers.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.journal_vouchers.getTableName(),
                    belongsToColumn: 'attachments',
                    belongsToId: journal_vouchers[i].id,
                },
                data[i].attachments,
                options,
            );
        }
        

        return journal_vouchers;
    }

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

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


        

        const updatePayload = {};
        
        if (data.voucher_number !== undefined) updatePayload.voucher_number = data.voucher_number;
        
        
        if (data.voucher_date !== undefined) updatePayload.voucher_date = data.voucher_date;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        if (data.total_debit !== undefined) updatePayload.total_debit = data.total_debit;
        
        
        if (data.total_credit !== undefined) updatePayload.total_credit = data.total_credit;
        
        
        if (data.is_balanced !== undefined) updatePayload.is_balanced = data.is_balanced;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.business !== undefined) {
            await journal_vouchers.setBusiness(
              
              data.business,
              
              { transaction }
            );
        }
        
        if (data.fiscal_year !== undefined) {
            await journal_vouchers.setFiscal_year(
              
              data.fiscal_year,
              
              { transaction }
            );
        }
        
        if (data.branch !== undefined) {
            await journal_vouchers.setBranch(
              
              data.branch,
              
              { transaction }
            );
        }
        
        if (data.voucher_type !== undefined) {
            await journal_vouchers.setVoucher_type(
              
              data.voucher_type,
              
              { transaction }
            );
        }
        

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.journal_vouchers.getTableName(),
                belongsToColumn: 'attachments',
                belongsToId: journal_vouchers.id,
            },
            data.attachments,
            options,
        );
        

        return journal_vouchers;
    }

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

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

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


        return journal_vouchers;
    }

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

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

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

        await journal_vouchers.destroy({
            transaction
        });

        return journal_vouchers;
    }

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

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

        if (!journal_vouchers) {
            return journal_vouchers;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.journal_lines_voucher = await journal_vouchers.getJournal_lines_voucher({
            transaction
        });
        
        
        
        
        output.voucher_approvals_voucher = await journal_vouchers.getVoucher_approvals_voucher({
            transaction
        });
        
        
        output.year_end_operations_generated_voucher = await journal_vouchers.getYear_end_operations_generated_voucher({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        output.business = await journal_vouchers.getBusiness({
            transaction
        });
        
        
        output.fiscal_year = await journal_vouchers.getFiscal_year({
            transaction
        });
        
        
        output.branch = await journal_vouchers.getBranch({
            transaction
        });
        
        
        output.voucher_type = await journal_vouchers.getVoucher_type({
            transaction
        });
        
        
        output.attachments = await journal_vouchers.getAttachments({
            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.branches,
        as: 'branch',
        
        where: filter.branch ? {
          [Op.or]: [
            { id: { [Op.in]: filter.branch.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.branch.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



      {
        model: db.file,
        as: 'attachments',
      },

    ];

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

            
            if (filter.voucher_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'journal_vouchers',
                        'voucher_number',
                        filter.voucher_number,
                    ),
                };
            }
            
            if (filter.description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'journal_vouchers',
                        'description',
                        filter.description,
                    ),
                };
            }
            

            
            

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    voucher_date: {
                    ...where.voucher_date,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.total_debitRange) {
                const [start, end] = filter.total_debitRange;

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    total_debit: {
                    ...where.total_debit,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.total_creditRange) {
                const [start, end] = filter.total_creditRange;

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

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

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

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


      

      

      

      



            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.journal_vouchers.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(
                        'journal_vouchers',
                        'voucher_number',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

