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

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

        const coin_conversions = await db.coin_conversions.create(
            {
                id: data.id || undefined,
        
        from_doodlecoins: data.from_doodlecoins
        ||
        null
            ,
            
        to_supercharged: data.to_supercharged
        ||
        null
            ,
            
        rate_from: data.rate_from
        ||
        null
            ,
            
        rate_to: data.rate_to
        ||
        null
            ,
            
        converted_at: data.converted_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await coin_conversions.setUser( data.user || null, {
            transaction,
        });
        

        

        

        return coin_conversions;
    }
    

    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 coin_conversionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                from_doodlecoins: item.from_doodlecoins
            ||
            null
            ,
            
                to_supercharged: item.to_supercharged
            ||
            null
            ,
            
                rate_from: item.rate_from
            ||
            null
            ,
            
                rate_to: item.rate_to
            ||
            null
            ,
            
                converted_at: item.converted_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return coin_conversions;
    }

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

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


        

        const updatePayload = {};
        
        if (data.from_doodlecoins !== undefined) updatePayload.from_doodlecoins = data.from_doodlecoins;
        
        
        if (data.to_supercharged !== undefined) updatePayload.to_supercharged = data.to_supercharged;
        
        
        if (data.rate_from !== undefined) updatePayload.rate_from = data.rate_from;
        
        
        if (data.rate_to !== undefined) updatePayload.rate_to = data.rate_to;
        
        
        if (data.converted_at !== undefined) updatePayload.converted_at = data.converted_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.user !== undefined) {
            await coin_conversions.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        

        
        

        

        return coin_conversions;
    }

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

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

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


        return coin_conversions;
    }

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

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

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

        await coin_conversions.destroy({
            transaction
        });

        return coin_conversions;
    }

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

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

        if (!coin_conversions) {
            return coin_conversions;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await coin_conversions.getUser({
            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.users,
        as: 'user',
        
        where: filter.user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            

            
            

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

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

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

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

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

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

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

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

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

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

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

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

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

    
};

