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

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

        const journal_entries = await db.journal_entries.create(
            {
                id: data.id || undefined,
        
        journal_number: data.journal_number
        ||
        null
            ,
            
        entry_date: data.entry_date
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        memo: data.memo
        ||
        null
            ,
            
        total_debit: data.total_debit
        ||
        null
            ,
            
        total_credit: data.total_credit
        ||
        null
            ,
            
        posted_at: data.posted_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await journal_entries.setPlant( data.plant || null, {
            transaction,
        });
        
        await journal_entries.setPosted_by( data.posted_by || null, {
            transaction,
        });
        

        

        

        return journal_entries;
    }
    

    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_entriesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                journal_number: item.journal_number
            ||
            null
            ,
            
                entry_date: item.entry_date
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                memo: item.memo
            ||
            null
            ,
            
                total_debit: item.total_debit
            ||
            null
            ,
            
                total_credit: item.total_credit
            ||
            null
            ,
            
                posted_at: item.posted_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return journal_entries;
    }

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

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


        

        const updatePayload = {};
        
        if (data.journal_number !== undefined) updatePayload.journal_number = data.journal_number;
        
        
        if (data.entry_date !== undefined) updatePayload.entry_date = data.entry_date;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.memo !== undefined) updatePayload.memo = data.memo;
        
        
        if (data.total_debit !== undefined) updatePayload.total_debit = data.total_debit;
        
        
        if (data.total_credit !== undefined) updatePayload.total_credit = data.total_credit;
        
        
        if (data.posted_at !== undefined) updatePayload.posted_at = data.posted_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.plant !== undefined) {
            await journal_entries.setPlant(
              
              data.plant,
              
              { transaction }
            );
        }
        
        if (data.posted_by !== undefined) {
            await journal_entries.setPosted_by(
              
              data.posted_by,
              
              { transaction }
            );
        }
        

        
        

        

        return journal_entries;
    }

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

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

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


        return journal_entries;
    }

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

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

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

        await journal_entries.destroy({
            transaction
        });

        return journal_entries;
    }

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

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

        if (!journal_entries) {
            return journal_entries;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.journal_lines_journal_entry = await journal_entries.getJournal_lines_journal_entry({
            transaction
        });
        
        
        
        
        
        output.plant = await journal_entries.getPlant({
            transaction
        });
        
        
        output.posted_by = await journal_entries.getPosted_by({
            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.plants,
        as: 'plant',
        
        where: filter.plant ? {
          [Op.or]: [
            { id: { [Op.in]: filter.plant.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.plant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

            
            if (filter.journal_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'journal_entries',
                        'journal_number',
                        filter.journal_number,
                    ),
                };
            }
            
            if (filter.memo) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'journal_entries',
                        'memo',
                        filter.memo,
                    ),
                };
            }
            

            
            

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    entry_date: {
                    ...where.entry_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.posted_atRange) {
                const [start, end] = filter.posted_atRange;

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    posted_at: {
                    ...where.posted_at,
                            [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.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_entries.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_entries',
                        'journal_number',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

