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

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

        const ads = await db.ads.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        ad_type: data.ad_type
        ||
        null
            ,
            
        promotional_text: data.promotional_text
        ||
        null
            ,
            
        custom_code: data.custom_code
        ||
        null
            ,
            
        destination_url: data.destination_url
        ||
        null
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
        starts_at: data.starts_at
        ||
        null
            ,
            
        ends_at: data.ends_at
        ||
        null
            ,
            
        impressions_count: data.impressions_count
        ||
        null
            ,
            
        clicks_count: data.clicks_count
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await ads.setPlacement( data.placement || null, {
            transaction,
        });
        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.ads.getTableName(),
                belongsToColumn: 'image',
                belongsToId: ads.id,
            },
            data.image,
            options,
        );
        

        return ads;
    }
    

    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 adsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                ad_type: item.ad_type
            ||
            null
            ,
            
                promotional_text: item.promotional_text
            ||
            null
            ,
            
                custom_code: item.custom_code
            ||
            null
            ,
            
                destination_url: item.destination_url
            ||
            null
            ,
            
                is_active: item.is_active
            ||
            false
        
            ,
            
                starts_at: item.starts_at
            ||
            null
            ,
            
                ends_at: item.ends_at
            ||
            null
            ,
            
                impressions_count: item.impressions_count
            ||
            null
            ,
            
                clicks_count: item.clicks_count
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        
        for (let i = 0; i < ads.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.ads.getTableName(),
                    belongsToColumn: 'image',
                    belongsToId: ads[i].id,
                },
                data[i].image,
                options,
            );
        }
        

        return ads;
    }

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

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.ad_type !== undefined) updatePayload.ad_type = data.ad_type;
        
        
        if (data.promotional_text !== undefined) updatePayload.promotional_text = data.promotional_text;
        
        
        if (data.custom_code !== undefined) updatePayload.custom_code = data.custom_code;
        
        
        if (data.destination_url !== undefined) updatePayload.destination_url = data.destination_url;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        if (data.starts_at !== undefined) updatePayload.starts_at = data.starts_at;
        
        
        if (data.ends_at !== undefined) updatePayload.ends_at = data.ends_at;
        
        
        if (data.impressions_count !== undefined) updatePayload.impressions_count = data.impressions_count;
        
        
        if (data.clicks_count !== undefined) updatePayload.clicks_count = data.clicks_count;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.placement !== undefined) {
            await ads.setPlacement(
              
              data.placement,
              
              { transaction }
            );
        }
        

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.ads.getTableName(),
                belongsToColumn: 'image',
                belongsToId: ads.id,
            },
            data.image,
            options,
        );
        

        return ads;
    }

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

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

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


        return ads;
    }

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

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

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

        await ads.destroy({
            transaction
        });

        return ads;
    }

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

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

        if (!ads) {
            return ads;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.ad_events_ad = await ads.getAd_events_ad({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.placement = await ads.getPlacement({
            transaction
        });
        
        
        output.image = await ads.getImage({
            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_placements,
        as: 'placement',
        
        where: filter.placement ? {
          [Op.or]: [
            { id: { [Op.in]: filter.placement.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.placement.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



      {
        model: db.file,
        as: 'image',
      },

    ];

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

            
            if (filter.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'ads',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.promotional_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'ads',
                        'promotional_text',
                        filter.promotional_text,
                    ),
                };
            }
            
            if (filter.custom_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'ads',
                        'custom_code',
                        filter.custom_code,
                    ),
                };
            }
            
            if (filter.destination_url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'ads',
                        'destination_url',
                        filter.destination_url,
                    ),
                };
            }
            

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

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

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

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

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

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

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

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

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

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

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

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


      



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

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

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

    
};

