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

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

        const ad_projects = await db.ad_projects.create(
            {
                id: data.id || undefined,
        
        project_name: data.project_name
        ||
        null
            ,
            
        channel: data.channel
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        creative_brief: data.creative_brief
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await ad_projects.setCampaign( data.campaign || null, {
            transaction,
        });
        
        await ad_projects.setBrand_voice_profile( data.brand_voice_profile || null, {
            transaction,
        });
        

        

        

        return ad_projects;
    }
    

    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_projectsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                project_name: item.project_name
            ||
            null
            ,
            
                channel: item.channel
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                creative_brief: item.creative_brief
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return ad_projects;
    }

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

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


        

        const updatePayload = {};
        
        if (data.project_name !== undefined) updatePayload.project_name = data.project_name;
        
        
        if (data.channel !== undefined) updatePayload.channel = data.channel;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.creative_brief !== undefined) updatePayload.creative_brief = data.creative_brief;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.campaign !== undefined) {
            await ad_projects.setCampaign(
              
              data.campaign,
              
              { transaction }
            );
        }
        
        if (data.brand_voice_profile !== undefined) {
            await ad_projects.setBrand_voice_profile(
              
              data.brand_voice_profile,
              
              { transaction }
            );
        }
        

        
        

        

        return ad_projects;
    }

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

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

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


        return ad_projects;
    }

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

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

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

        await ad_projects.destroy({
            transaction
        });

        return ad_projects;
    }

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

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

        if (!ad_projects) {
            return ad_projects;
        }

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

        
        
        
        
        
        
        
        
        output.six_hat_sessions_ad_project = await ad_projects.getSix_hat_sessions_ad_project({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        output.ad_creatives_ad_project = await ad_projects.getAd_creatives_ad_project({
            transaction
        });
        
        
        output.generation_runs_ad_project = await ad_projects.getGeneration_runs_ad_project({
            transaction
        });
        
        
        
        
        
        
        output.platform_metrics_ad_project = await ad_projects.getPlatform_metrics_ad_project({
            transaction
        });
        
        
        
        
        
        
        output.campaign = await ad_projects.getCampaign({
            transaction
        });
        
        
        output.brand_voice_profile = await ad_projects.getBrand_voice_profile({
            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.campaigns,
        as: 'campaign',
        
        where: filter.campaign ? {
          [Op.or]: [
            { id: { [Op.in]: filter.campaign.split('|').map(term => Utils.uuid(term)) } },
            {
              campaign_name: {
                [Op.or]: filter.campaign.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.brand_voice_profiles,
        as: 'brand_voice_profile',
        
        where: filter.brand_voice_profile ? {
          [Op.or]: [
            { id: { [Op.in]: filter.brand_voice_profile.split('|').map(term => Utils.uuid(term)) } },
            {
              profile_name: {
                [Op.or]: filter.brand_voice_profile.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.project_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'ad_projects',
                        'project_name',
                        filter.project_name,
                    ),
                };
            }
            
            if (filter.creative_brief) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'ad_projects',
                        'creative_brief',
                        filter.creative_brief,
                    ),
                };
            }
            

            
            

            

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

            
            if (filter.channel) {
                where = {
                    ...where,
                channel: filter.channel,
            };
            }
            
            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.ad_projects.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_projects',
                        'project_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

