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

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

        const currency_rates = await db.currency_rates.create(
            {
                id: data.id || undefined,
        
        rate_date: data.rate_date
        ||
        null
            ,
            
        rate: data.rate
        ||
        null
            ,
            
        source: data.source
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await currency_rates.setBusiness( data.business || null, {
            transaction,
        });
        
        await currency_rates.setFrom_currency( data.from_currency || null, {
            transaction,
        });
        
        await currency_rates.setTo_currency( data.to_currency || null, {
            transaction,
        });
        

        

        

        return currency_rates;
    }
    

    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 currency_ratesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                rate_date: item.rate_date
            ||
            null
            ,
            
                rate: item.rate
            ||
            null
            ,
            
                source: item.source
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return currency_rates;
    }

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

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


        

        const updatePayload = {};
        
        if (data.rate_date !== undefined) updatePayload.rate_date = data.rate_date;
        
        
        if (data.rate !== undefined) updatePayload.rate = data.rate;
        
        
        if (data.source !== undefined) updatePayload.source = data.source;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.business !== undefined) {
            await currency_rates.setBusiness(
              
              data.business,
              
              { transaction }
            );
        }
        
        if (data.from_currency !== undefined) {
            await currency_rates.setFrom_currency(
              
              data.from_currency,
              
              { transaction }
            );
        }
        
        if (data.to_currency !== undefined) {
            await currency_rates.setTo_currency(
              
              data.to_currency,
              
              { transaction }
            );
        }
        

        
        

        

        return currency_rates;
    }

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

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

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


        return currency_rates;
    }

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

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

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

        await currency_rates.destroy({
            transaction
        });

        return currency_rates;
    }

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

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

        if (!currency_rates) {
            return currency_rates;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.business = await currency_rates.getBusiness({
            transaction
        });
        
        
        output.from_currency = await currency_rates.getFrom_currency({
            transaction
        });
        
        
        output.to_currency = await currency_rates.getTo_currency({
            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.currencies,
        as: 'from_currency',
        
        where: filter.from_currency ? {
          [Op.or]: [
            { id: { [Op.in]: filter.from_currency.split('|').map(term => Utils.uuid(term)) } },
            {
              code: {
                [Op.or]: filter.from_currency.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

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

            
            

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    rate: {
                    ...where.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.currency_rates.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(
                        'currency_rates',
                        'source',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

