
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,
        
        base_currency: data.base_currency
        ||
        null
            ,
            
        quote_currency: data.quote_currency
        ||
        null
            ,
            
        rate: data.rate
        ||
        null
            ,
            
        effective_at: data.effective_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await currency_rates.setTenant( data.tenant || null, {
            transaction,
        });
        
        await currency_rates.setOrganizations( data.organizations || 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,
                
                base_currency: item.base_currency
            ||
            null
            ,
            
                quote_currency: item.quote_currency
            ||
            null
            ,
            
                rate: item.rate
            ||
            null
            ,
            
                effective_at: item.effective_at
            ||
            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 globalAccess = currentUser.app_role?.globalAccess;

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


        

        const updatePayload = {};
        
        if (data.base_currency !== undefined) updatePayload.base_currency = data.base_currency;
        
        
        if (data.quote_currency !== undefined) updatePayload.quote_currency = data.quote_currency;
        
        
        if (data.rate !== undefined) updatePayload.rate = data.rate;
        
        
        if (data.effective_at !== undefined) updatePayload.effective_at = data.effective_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.tenant !== undefined) {
            await currency_rates.setTenant(
              
              data.tenant,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await currency_rates.setOrganizations(
              
              data.organizations,
              
              { 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.tenant = await currency_rates.getTenant({
            transaction
        });
        
        
        output.organizations = await currency_rates.getOrganizations({
            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.tenants,
        as: 'tenant',
        
        where: filter.tenant ? {
          [Op.or]: [
            { id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

            

            
            

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

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

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

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

            
            if (filter.base_currency) {
                where = {
                    ...where,
                base_currency: filter.base_currency,
            };
            }
            
            if (filter.quote_currency) {
                where = {
                    ...where,
                quote_currency: filter.quote_currency,
            };
            }
            


      

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

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

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

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

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

    
};

