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

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

        const platform_metrics = await db.platform_metrics.create(
            {
                id: data.id || undefined,
        
        platform: data.platform
        ||
        null
            ,
            
        metric_date: data.metric_date
        ||
        null
            ,
            
        spend: data.spend
        ||
        null
            ,
            
        impressions: data.impressions
        ||
        null
            ,
            
        clicks: data.clicks
        ||
        null
            ,
            
        ctr: data.ctr
        ||
        null
            ,
            
        conversions: data.conversions
        ||
        null
            ,
            
        cpa: data.cpa
        ||
        null
            ,
            
        roas: data.roas
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await platform_metrics.setAd_project( data.ad_project || null, {
            transaction,
        });
        

        

        

        return platform_metrics;
    }
    

    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 platform_metricsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                platform: item.platform
            ||
            null
            ,
            
                metric_date: item.metric_date
            ||
            null
            ,
            
                spend: item.spend
            ||
            null
            ,
            
                impressions: item.impressions
            ||
            null
            ,
            
                clicks: item.clicks
            ||
            null
            ,
            
                ctr: item.ctr
            ||
            null
            ,
            
                conversions: item.conversions
            ||
            null
            ,
            
                cpa: item.cpa
            ||
            null
            ,
            
                roas: item.roas
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return platform_metrics;
    }

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

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


        

        const updatePayload = {};
        
        if (data.platform !== undefined) updatePayload.platform = data.platform;
        
        
        if (data.metric_date !== undefined) updatePayload.metric_date = data.metric_date;
        
        
        if (data.spend !== undefined) updatePayload.spend = data.spend;
        
        
        if (data.impressions !== undefined) updatePayload.impressions = data.impressions;
        
        
        if (data.clicks !== undefined) updatePayload.clicks = data.clicks;
        
        
        if (data.ctr !== undefined) updatePayload.ctr = data.ctr;
        
        
        if (data.conversions !== undefined) updatePayload.conversions = data.conversions;
        
        
        if (data.cpa !== undefined) updatePayload.cpa = data.cpa;
        
        
        if (data.roas !== undefined) updatePayload.roas = data.roas;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.ad_project !== undefined) {
            await platform_metrics.setAd_project(
              
              data.ad_project,
              
              { transaction }
            );
        }
        

        
        

        

        return platform_metrics;
    }

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

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

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


        return platform_metrics;
    }

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

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

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

        await platform_metrics.destroy({
            transaction
        });

        return platform_metrics;
    }

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

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

        if (!platform_metrics) {
            return platform_metrics;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.ad_project = await platform_metrics.getAd_project({
            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.ad_projects,
        as: 'ad_project',
        
        where: filter.ad_project ? {
          [Op.or]: [
            { id: { [Op.in]: filter.ad_project.split('|').map(term => Utils.uuid(term)) } },
            {
              project_name: {
                [Op.or]: filter.ad_project.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            

            
            

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


      



            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.platform_metrics.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(
                        'platform_metrics',
                        'platform',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

