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

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

        const six_hat_sessions = await db.six_hat_sessions.create(
            {
                id: data.id || undefined,
        
        session_name: data.session_name
        ||
        null
            ,
            
        prompt_context: data.prompt_context
        ||
        null
            ,
            
        white_hat_notes: data.white_hat_notes
        ||
        null
            ,
            
        red_hat_notes: data.red_hat_notes
        ||
        null
            ,
            
        black_hat_notes: data.black_hat_notes
        ||
        null
            ,
            
        yellow_hat_notes: data.yellow_hat_notes
        ||
        null
            ,
            
        green_hat_notes: data.green_hat_notes
        ||
        null
            ,
            
        blue_hat_notes: data.blue_hat_notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await six_hat_sessions.setCampaign( data.campaign || null, {
            transaction,
        });
        
        await six_hat_sessions.setAd_project( data.ad_project || null, {
            transaction,
        });
        

        

        

        return six_hat_sessions;
    }
    

    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 six_hat_sessionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                session_name: item.session_name
            ||
            null
            ,
            
                prompt_context: item.prompt_context
            ||
            null
            ,
            
                white_hat_notes: item.white_hat_notes
            ||
            null
            ,
            
                red_hat_notes: item.red_hat_notes
            ||
            null
            ,
            
                black_hat_notes: item.black_hat_notes
            ||
            null
            ,
            
                yellow_hat_notes: item.yellow_hat_notes
            ||
            null
            ,
            
                green_hat_notes: item.green_hat_notes
            ||
            null
            ,
            
                blue_hat_notes: item.blue_hat_notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return six_hat_sessions;
    }

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

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


        

        const updatePayload = {};
        
        if (data.session_name !== undefined) updatePayload.session_name = data.session_name;
        
        
        if (data.prompt_context !== undefined) updatePayload.prompt_context = data.prompt_context;
        
        
        if (data.white_hat_notes !== undefined) updatePayload.white_hat_notes = data.white_hat_notes;
        
        
        if (data.red_hat_notes !== undefined) updatePayload.red_hat_notes = data.red_hat_notes;
        
        
        if (data.black_hat_notes !== undefined) updatePayload.black_hat_notes = data.black_hat_notes;
        
        
        if (data.yellow_hat_notes !== undefined) updatePayload.yellow_hat_notes = data.yellow_hat_notes;
        
        
        if (data.green_hat_notes !== undefined) updatePayload.green_hat_notes = data.green_hat_notes;
        
        
        if (data.blue_hat_notes !== undefined) updatePayload.blue_hat_notes = data.blue_hat_notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return six_hat_sessions;
    }

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

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

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


        return six_hat_sessions;
    }

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

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

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

        await six_hat_sessions.destroy({
            transaction
        });

        return six_hat_sessions;
    }

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

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

        if (!six_hat_sessions) {
            return six_hat_sessions;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.campaign = await six_hat_sessions.getCampaign({
            transaction
        });
        
        
        output.ad_project = await six_hat_sessions.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.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.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.session_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'six_hat_sessions',
                        'session_name',
                        filter.session_name,
                    ),
                };
            }
            
            if (filter.prompt_context) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'six_hat_sessions',
                        'prompt_context',
                        filter.prompt_context,
                    ),
                };
            }
            
            if (filter.white_hat_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'six_hat_sessions',
                        'white_hat_notes',
                        filter.white_hat_notes,
                    ),
                };
            }
            
            if (filter.red_hat_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'six_hat_sessions',
                        'red_hat_notes',
                        filter.red_hat_notes,
                    ),
                };
            }
            
            if (filter.black_hat_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'six_hat_sessions',
                        'black_hat_notes',
                        filter.black_hat_notes,
                    ),
                };
            }
            
            if (filter.yellow_hat_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'six_hat_sessions',
                        'yellow_hat_notes',
                        filter.yellow_hat_notes,
                    ),
                };
            }
            
            if (filter.green_hat_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'six_hat_sessions',
                        'green_hat_notes',
                        filter.green_hat_notes,
                    ),
                };
            }
            
            if (filter.blue_hat_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'six_hat_sessions',
                        'blue_hat_notes',
                        filter.blue_hat_notes,
                    ),
                };
            }
            

            
            

            

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

            


      

      



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

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

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

    
};

