
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,
        
        entryNumber: data.entryNumber
        ||
        null
            ,
            
        entryDate: data.entryDate
        ||
        null
            ,
            
        journalType: data.journalType
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
        reference: data.reference
        ||
        null
            ,
            
        postedAt: data.postedAt
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await journal_entries.setPayrollRun( data.payrollRun || null, {
            transaction,
        });
        
        await journal_entries.setReversalOfEntry( data.reversalOfEntry || null, {
            transaction,
        });
        
        await journal_entries.setPostedByUser( data.postedByUser || 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,
                
                entryNumber: item.entryNumber
            ||
            null
            ,
            
                entryDate: item.entryDate
            ||
            null
            ,
            
                journalType: item.journalType
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                description: item.description
            ||
            null
            ,
            
                reference: item.reference
            ||
            null
            ,
            
                postedAt: item.postedAt
            ||
            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.entryNumber !== undefined) updatePayload.entryNumber = data.entryNumber;
        
        
        if (data.entryDate !== undefined) updatePayload.entryDate = data.entryDate;
        
        
        if (data.journalType !== undefined) updatePayload.journalType = data.journalType;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        if (data.reference !== undefined) updatePayload.reference = data.reference;
        
        
        if (data.postedAt !== undefined) updatePayload.postedAt = data.postedAt;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.payrollRun !== undefined) {
            await journal_entries.setPayrollRun(
              
              data.payrollRun,
              
              { transaction }
            );
        }
        
        if (data.reversalOfEntry !== undefined) {
            await journal_entries.setReversalOfEntry(
              
              data.reversalOfEntry,
              
              { transaction }
            );
        }
        
        if (data.postedByUser !== undefined) {
            await journal_entries.setPostedByUser(
              
              data.postedByUser,
              
              { 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.payroll_runs_journalEntry = await journal_entries.getPayroll_runs_journalEntry({
            transaction
        });
        
        
        
        
        
        
        output.journal_lines_journalEntry = await journal_entries.getJournal_lines_journalEntry({
            transaction
        });
        
        
        
        output.ap_invoices_journalEntry = await journal_entries.getAp_invoices_journalEntry({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.payrollRun = await journal_entries.getPayrollRun({
            transaction
        });
        
        
        output.reversalOfEntry = await journal_entries.getReversalOfEntry({
            transaction
        });
        
        
        output.postedByUser = await journal_entries.getPostedByUser({
            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.payroll_runs,
        as: 'payrollRun',
        
        where: filter.payrollRun ? {
          [Op.or]: [
            { id: { [Op.in]: filter.payrollRun.split('|').map(term => Utils.uuid(term)) } },
            {
              status: {
                [Op.or]: filter.payrollRun.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



    ];

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

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

            
            

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

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

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

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

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

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

            
            if (filter.journalType) {
                where = {
                    ...where,
                journalType: filter.journalType,
            };
            }
            
            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',
                        'entryNumber',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

