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

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

        const ad_creatives = await db.ad_creatives.create(
            {
                id: data.id || undefined,
        
        creative_name: data.creative_name
        ||
        null
            ,
            
        creative_format: data.creative_format
        ||
        null
            ,
            
        primary_text: data.primary_text
        ||
        null
            ,
            
        headline: data.headline
        ||
        null
            ,
            
        description_text: data.description_text
        ||
        null
            ,
            
        call_to_action: data.call_to_action
        ||
        null
            ,
            
        targeting_notes: data.targeting_notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

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

        return ad_creatives;
    }
    

    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 ad_creativesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                creative_name: item.creative_name
            ||
            null
            ,
            
                creative_format: item.creative_format
            ||
            null
            ,
            
                primary_text: item.primary_text
            ||
            null
            ,
            
                headline: item.headline
            ||
            null
            ,
            
                description_text: item.description_text
            ||
            null
            ,
            
                call_to_action: item.call_to_action
            ||
            null
            ,
            
                targeting_notes: item.targeting_notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return ad_creatives;
    }

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

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


        

        const updatePayload = {};
        
        if (data.creative_name !== undefined) updatePayload.creative_name = data.creative_name;
        
        
        if (data.creative_format !== undefined) updatePayload.creative_format = data.creative_format;
        
        
        if (data.primary_text !== undefined) updatePayload.primary_text = data.primary_text;
        
        
        if (data.headline !== undefined) updatePayload.headline = data.headline;
        
        
        if (data.description_text !== undefined) updatePayload.description_text = data.description_text;
        
        
        if (data.call_to_action !== undefined) updatePayload.call_to_action = data.call_to_action;
        
        
        if (data.targeting_notes !== undefined) updatePayload.targeting_notes = data.targeting_notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

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

        return ad_creatives;
    }

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

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

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


        return ad_creatives;
    }

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

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

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

        await ad_creatives.destroy({
            transaction
        });

        return ad_creatives;
    }

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

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

        if (!ad_creatives) {
            return ad_creatives;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.ad_project = await ad_creatives.getAd_project({
            transaction
        });
        
        
        output.creative_images = await ad_creatives.getCreative_images({
            transaction
        });
        
        
        output.creative_files = await ad_creatives.getCreative_files({
            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}%` }))
              }
            },
          ]
        } : {},
        
      },



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

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

    ];

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

            
            if (filter.creative_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'ad_creatives',
                        'creative_name',
                        filter.creative_name,
                    ),
                };
            }
            
            if (filter.primary_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'ad_creatives',
                        'primary_text',
                        filter.primary_text,
                    ),
                };
            }
            
            if (filter.headline) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'ad_creatives',
                        'headline',
                        filter.headline,
                    ),
                };
            }
            
            if (filter.description_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'ad_creatives',
                        'description_text',
                        filter.description_text,
                    ),
                };
            }
            
            if (filter.call_to_action) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'ad_creatives',
                        'call_to_action',
                        filter.call_to_action,
                    ),
                };
            }
            
            if (filter.targeting_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'ad_creatives',
                        'targeting_notes',
                        filter.targeting_notes,
                    ),
                };
            }
            

            
            

            

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

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


      



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

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

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

    
};

