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

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

        const ledger_entries = await db.ledger_entries.create(
            {
                id: data.id || undefined,
        
        entry_reference: data.entry_reference
        ||
        null
            ,
            
        entry_date: data.entry_date
        ||
        null
            ,
            
        entry_type: data.entry_type
        ||
        null
            ,
            
        currency: data.currency
        ||
        null
            ,
            
        debit_amount: data.debit_amount
        ||
        null
            ,
            
        credit_amount: data.credit_amount
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
        record_type: data.record_type
        ||
        null
            ,
            
        record_key: data.record_key
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await ledger_entries.setOrganization(currentUser.organization.id || null, {
            transaction,
        });
        
        await ledger_entries.setFiscal_year( data.fiscal_year || null, {
            transaction,
        });
        

        

        

        return ledger_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 ledger_entriesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                entry_reference: item.entry_reference
            ||
            null
            ,
            
                entry_date: item.entry_date
            ||
            null
            ,
            
                entry_type: item.entry_type
            ||
            null
            ,
            
                currency: item.currency
            ||
            null
            ,
            
                debit_amount: item.debit_amount
            ||
            null
            ,
            
                credit_amount: item.credit_amount
            ||
            null
            ,
            
                description: item.description
            ||
            null
            ,
            
                record_type: item.record_type
            ||
            null
            ,
            
                record_key: item.record_key
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return ledger_entries;
    }

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

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


        

        const updatePayload = {};
        
        if (data.entry_reference !== undefined) updatePayload.entry_reference = data.entry_reference;
        
        
        if (data.entry_date !== undefined) updatePayload.entry_date = data.entry_date;
        
        
        if (data.entry_type !== undefined) updatePayload.entry_type = data.entry_type;
        
        
        if (data.currency !== undefined) updatePayload.currency = data.currency;
        
        
        if (data.debit_amount !== undefined) updatePayload.debit_amount = data.debit_amount;
        
        
        if (data.credit_amount !== undefined) updatePayload.credit_amount = data.credit_amount;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        if (data.record_type !== undefined) updatePayload.record_type = data.record_type;
        
        
        if (data.record_key !== undefined) updatePayload.record_key = data.record_key;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.organization !== undefined) {
            await ledger_entries.setOrganization(
              
              (globalAccess ? data.organization : currentUser.organization.id),
              
              { transaction }
            );
        }
        
        if (data.fiscal_year !== undefined) {
            await ledger_entries.setFiscal_year(
              
              data.fiscal_year,
              
              { transaction }
            );
        }
        

        
        

        

        return ledger_entries;
    }

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

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

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


        return ledger_entries;
    }

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

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

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

        await ledger_entries.destroy({
            transaction
        });

        return ledger_entries;
    }

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

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

        if (!ledger_entries) {
            return ledger_entries;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.organization = await ledger_entries.getOrganization({
            transaction
        });
        
        
        output.fiscal_year = await ledger_entries.getFiscal_year({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           globalAccess,  options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        
        const user = (options && options.currentUser) || null;
        const userOrganizations = (user && user.organizations?.id) || null;
        

        
        if (userOrganizations) {
            if (options?.currentUser?.organizationsId) {
                where.organizationsId = options.currentUser.organizationsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

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

    let include = [

      {
        model: db.organizations,
        as: 'organization',
        
      },

      {
        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)) } },
            {
              name: {
                [Op.or]: filter.fiscal_year.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.entry_reference) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'ledger_entries',
                        'entry_reference',
                        filter.entry_reference,
                    ),
                };
            }
            
            if (filter.description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'ledger_entries',
                        'description',
                        filter.description,
                    ),
                };
            }
            
            if (filter.record_type) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'ledger_entries',
                        'record_type',
                        filter.record_type,
                    ),
                };
            }
            
            if (filter.record_key) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'ledger_entries',
                        'record_key',
                        filter.record_key,
                    ),
                };
            }
            

            
            

            
            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.debit_amountRange) {
                const [start, end] = filter.debit_amountRange;

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

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

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

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

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

            
            if (filter.entry_type) {
                where = {
                    ...where,
                entry_type: filter.entry_type,
            };
            }
            
            if (filter.currency) {
                where = {
                    ...where,
                currency: filter.currency,
            };
            }
            


      
      if (filter.organization) {
        const listItems = filter.organization.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          organizationId: {[Op.or]: listItems}
        };
      }
      

      



            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,
                        },
                    };
                }
            }
        }
        

        
        if (globalAccess) {
            delete where.organizationsId;
        }
        

        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.ledger_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,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'ledger_entries',
                        'entry_reference',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

