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

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

        const campaigns = await db.campaigns.create(
            {
                id: data.id || undefined,
        
        campaign_name: data.campaign_name
        ||
        null
            ,
            
        campaign_type: data.campaign_type
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        objective: data.objective
        ||
        null
            ,
            
        primary_audience: data.primary_audience
        ||
        null
            ,
            
        budget_amount: data.budget_amount
        ||
        null
            ,
            
        budget_currency: data.budget_currency
        ||
        null
            ,
            
        start_at: data.start_at
        ||
        null
            ,
            
        end_at: data.end_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await campaigns.setBrand( data.brand || null, {
            transaction,
        });
        

        

        

        return campaigns;
    }
    

    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 campaignsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                campaign_name: item.campaign_name
            ||
            null
            ,
            
                campaign_type: item.campaign_type
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                objective: item.objective
            ||
            null
            ,
            
                primary_audience: item.primary_audience
            ||
            null
            ,
            
                budget_amount: item.budget_amount
            ||
            null
            ,
            
                budget_currency: item.budget_currency
            ||
            null
            ,
            
                start_at: item.start_at
            ||
            null
            ,
            
                end_at: item.end_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return campaigns;
    }

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

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


        

        const updatePayload = {};
        
        if (data.campaign_name !== undefined) updatePayload.campaign_name = data.campaign_name;
        
        
        if (data.campaign_type !== undefined) updatePayload.campaign_type = data.campaign_type;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.objective !== undefined) updatePayload.objective = data.objective;
        
        
        if (data.primary_audience !== undefined) updatePayload.primary_audience = data.primary_audience;
        
        
        if (data.budget_amount !== undefined) updatePayload.budget_amount = data.budget_amount;
        
        
        if (data.budget_currency !== undefined) updatePayload.budget_currency = data.budget_currency;
        
        
        if (data.start_at !== undefined) updatePayload.start_at = data.start_at;
        
        
        if (data.end_at !== undefined) updatePayload.end_at = data.end_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.brand !== undefined) {
            await campaigns.setBrand(
              
              data.brand,
              
              { transaction }
            );
        }
        

        
        

        

        return campaigns;
    }

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

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

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


        return campaigns;
    }

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

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

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

        await campaigns.destroy({
            transaction
        });

        return campaigns;
    }

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

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

        if (!campaigns) {
            return campaigns;
        }

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

        
        
        
        
        
        
        
        
        output.six_hat_sessions_campaign = await campaigns.getSix_hat_sessions_campaign({
            transaction
        });
        
        
        
        
        
        
        
        output.campaign_brain_configs_campaign = await campaigns.getCampaign_brain_configs_campaign({
            transaction
        });
        
        
        
        
        output.ad_projects_campaign = await campaigns.getAd_projects_campaign({
            transaction
        });
        
        
        
        
        
        
        
        output.learning_signals_campaign = await campaigns.getLearning_signals_campaign({
            transaction
        });
        
        
        
        
        
        
        
        output.brand = await campaigns.getBrand({
            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.brands,
        as: 'brand',
        
        where: filter.brand ? {
          [Op.or]: [
            { id: { [Op.in]: filter.brand.split('|').map(term => Utils.uuid(term)) } },
            {
              brand_name: {
                [Op.or]: filter.brand.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.campaign_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'campaigns',
                        'campaign_name',
                        filter.campaign_name,
                    ),
                };
            }
            
            if (filter.objective) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'campaigns',
                        'objective',
                        filter.objective,
                    ),
                };
            }
            
            if (filter.primary_audience) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'campaigns',
                        'primary_audience',
                        filter.primary_audience,
                    ),
                };
            }
            
            if (filter.budget_currency) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'campaigns',
                        'budget_currency',
                        filter.budget_currency,
                    ),
                };
            }
            

            
            
            if (filter.calendarStart && filter.calendarEnd) {
                where = {
                    ...where,
                    [Op.or]: [
                        {
                            start_at: {
                                [Op.between]: [filter.calendarStart, filter.calendarEnd],
                            },
                    },
                {
                    end_at: {
                        [Op.between]: [filter.calendarStart, filter.calendarEnd],
                    },
                },
                ],
            };
            }
            

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

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

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

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

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

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

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

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

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


      



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

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

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

    
};

