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

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

        const journal_lines = await db.journal_lines.create(
            {
                id: data.id || undefined,
        
        line_no: data.line_no
        ||
        null
            ,
            
        debit: data.debit
        ||
        null
            ,
            
        credit: data.credit
        ||
        null
            ,
            
        currency_amount: data.currency_amount
        ||
        null
            ,
            
        exchange_rate: data.exchange_rate
        ||
        null
            ,
            
        line_description: data.line_description
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await journal_lines.setVoucher( data.voucher || null, {
            transaction,
        });
        
        await journal_lines.setAccount( data.account || null, {
            transaction,
        });
        
        await journal_lines.setCurrency( data.currency || null, {
            transaction,
        });
        
        await journal_lines.setCounterparty( data.counterparty || null, {
            transaction,
        });
        
        await journal_lines.setCost_center( data.cost_center || null, {
            transaction,
        });
        
        await journal_lines.setProject( data.project || null, {
            transaction,
        });
        
        await journal_lines.setContract( data.contract || null, {
            transaction,
        });
        
        await journal_lines.setAnalytic_level_1( data.analytic_level_1 || null, {
            transaction,
        });
        
        await journal_lines.setAnalytic_level_2( data.analytic_level_2 || null, {
            transaction,
        });
        
        await journal_lines.setAnalytic_level_3( data.analytic_level_3 || null, {
            transaction,
        });
        
        await journal_lines.setAnalytic_level_4( data.analytic_level_4 || null, {
            transaction,
        });
        
        await journal_lines.setAnalytic_level_5( data.analytic_level_5 || null, {
            transaction,
        });
        
        await journal_lines.setAnalytic_level_6( data.analytic_level_6 || null, {
            transaction,
        });
        
        await journal_lines.setAnalytic_level_7( data.analytic_level_7 || null, {
            transaction,
        });
        
        await journal_lines.setAnalytic_level_8( data.analytic_level_8 || null, {
            transaction,
        });
        
        await journal_lines.setAnalytic_level_9( data.analytic_level_9 || null, {
            transaction,
        });
        
        await journal_lines.setAnalytic_level_10( data.analytic_level_10 || null, {
            transaction,
        });
        

        

        

        return journal_lines;
    }
    

    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_linesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                line_no: item.line_no
            ||
            null
            ,
            
                debit: item.debit
            ||
            null
            ,
            
                credit: item.credit
            ||
            null
            ,
            
                currency_amount: item.currency_amount
            ||
            null
            ,
            
                exchange_rate: item.exchange_rate
            ||
            null
            ,
            
                line_description: item.line_description
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return journal_lines;
    }

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

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


        

        const updatePayload = {};
        
        if (data.line_no !== undefined) updatePayload.line_no = data.line_no;
        
        
        if (data.debit !== undefined) updatePayload.debit = data.debit;
        
        
        if (data.credit !== undefined) updatePayload.credit = data.credit;
        
        
        if (data.currency_amount !== undefined) updatePayload.currency_amount = data.currency_amount;
        
        
        if (data.exchange_rate !== undefined) updatePayload.exchange_rate = data.exchange_rate;
        
        
        if (data.line_description !== undefined) updatePayload.line_description = data.line_description;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.voucher !== undefined) {
            await journal_lines.setVoucher(
              
              data.voucher,
              
              { transaction }
            );
        }
        
        if (data.account !== undefined) {
            await journal_lines.setAccount(
              
              data.account,
              
              { transaction }
            );
        }
        
        if (data.currency !== undefined) {
            await journal_lines.setCurrency(
              
              data.currency,
              
              { transaction }
            );
        }
        
        if (data.counterparty !== undefined) {
            await journal_lines.setCounterparty(
              
              data.counterparty,
              
              { transaction }
            );
        }
        
        if (data.cost_center !== undefined) {
            await journal_lines.setCost_center(
              
              data.cost_center,
              
              { transaction }
            );
        }
        
        if (data.project !== undefined) {
            await journal_lines.setProject(
              
              data.project,
              
              { transaction }
            );
        }
        
        if (data.contract !== undefined) {
            await journal_lines.setContract(
              
              data.contract,
              
              { transaction }
            );
        }
        
        if (data.analytic_level_1 !== undefined) {
            await journal_lines.setAnalytic_level_1(
              
              data.analytic_level_1,
              
              { transaction }
            );
        }
        
        if (data.analytic_level_2 !== undefined) {
            await journal_lines.setAnalytic_level_2(
              
              data.analytic_level_2,
              
              { transaction }
            );
        }
        
        if (data.analytic_level_3 !== undefined) {
            await journal_lines.setAnalytic_level_3(
              
              data.analytic_level_3,
              
              { transaction }
            );
        }
        
        if (data.analytic_level_4 !== undefined) {
            await journal_lines.setAnalytic_level_4(
              
              data.analytic_level_4,
              
              { transaction }
            );
        }
        
        if (data.analytic_level_5 !== undefined) {
            await journal_lines.setAnalytic_level_5(
              
              data.analytic_level_5,
              
              { transaction }
            );
        }
        
        if (data.analytic_level_6 !== undefined) {
            await journal_lines.setAnalytic_level_6(
              
              data.analytic_level_6,
              
              { transaction }
            );
        }
        
        if (data.analytic_level_7 !== undefined) {
            await journal_lines.setAnalytic_level_7(
              
              data.analytic_level_7,
              
              { transaction }
            );
        }
        
        if (data.analytic_level_8 !== undefined) {
            await journal_lines.setAnalytic_level_8(
              
              data.analytic_level_8,
              
              { transaction }
            );
        }
        
        if (data.analytic_level_9 !== undefined) {
            await journal_lines.setAnalytic_level_9(
              
              data.analytic_level_9,
              
              { transaction }
            );
        }
        
        if (data.analytic_level_10 !== undefined) {
            await journal_lines.setAnalytic_level_10(
              
              data.analytic_level_10,
              
              { transaction }
            );
        }
        

        
        

        

        return journal_lines;
    }

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

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

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


        return journal_lines;
    }

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

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

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

        await journal_lines.destroy({
            transaction
        });

        return journal_lines;
    }

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

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

        if (!journal_lines) {
            return journal_lines;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.voucher = await journal_lines.getVoucher({
            transaction
        });
        
        
        output.account = await journal_lines.getAccount({
            transaction
        });
        
        
        output.currency = await journal_lines.getCurrency({
            transaction
        });
        
        
        output.counterparty = await journal_lines.getCounterparty({
            transaction
        });
        
        
        output.cost_center = await journal_lines.getCost_center({
            transaction
        });
        
        
        output.project = await journal_lines.getProject({
            transaction
        });
        
        
        output.contract = await journal_lines.getContract({
            transaction
        });
        
        
        output.analytic_level_1 = await journal_lines.getAnalytic_level_1({
            transaction
        });
        
        
        output.analytic_level_2 = await journal_lines.getAnalytic_level_2({
            transaction
        });
        
        
        output.analytic_level_3 = await journal_lines.getAnalytic_level_3({
            transaction
        });
        
        
        output.analytic_level_4 = await journal_lines.getAnalytic_level_4({
            transaction
        });
        
        
        output.analytic_level_5 = await journal_lines.getAnalytic_level_5({
            transaction
        });
        
        
        output.analytic_level_6 = await journal_lines.getAnalytic_level_6({
            transaction
        });
        
        
        output.analytic_level_7 = await journal_lines.getAnalytic_level_7({
            transaction
        });
        
        
        output.analytic_level_8 = await journal_lines.getAnalytic_level_8({
            transaction
        });
        
        
        output.analytic_level_9 = await journal_lines.getAnalytic_level_9({
            transaction
        });
        
        
        output.analytic_level_10 = await journal_lines.getAnalytic_level_10({
            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.journal_vouchers,
        as: 'voucher',
        
        where: filter.voucher ? {
          [Op.or]: [
            { id: { [Op.in]: filter.voucher.split('|').map(term => Utils.uuid(term)) } },
            {
              voucher_number: {
                [Op.or]: filter.voucher.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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



    ];

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

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

            
            

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

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

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

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

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

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

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

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

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

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

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

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

            


      

      

      

      

      

      

      

      

      

      

      

      

      

      

      

      

      



            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_lines.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_lines',
                        'line_description',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

