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

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

        const fill_sessions = await db.fill_sessions.create(
            {
                id: data.id || undefined,
        
        session_name: data.session_name
        ||
        null
            ,
            
        started: data.started
        ||
        null
            ,
            
        ended: data.ended
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        response_cache: data.response_cache
        ||
        null
            ,
            
        progress_percent: data.progress_percent
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await fill_sessions.setSurvey( data.survey || null, {
            transaction,
        });
        
        await fill_sessions.setAi_model( data.ai_model || null, {
            transaction,
        });
        
        await fill_sessions.setApi_key( data.api_key || null, {
            transaction,
        });
        

        

        

        return fill_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 fill_sessionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                session_name: item.session_name
            ||
            null
            ,
            
                started: item.started
            ||
            null
            ,
            
                ended: item.ended
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                response_cache: item.response_cache
            ||
            null
            ,
            
                progress_percent: item.progress_percent
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return fill_sessions;
    }

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

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


        

        const updatePayload = {};
        
        if (data.session_name !== undefined) updatePayload.session_name = data.session_name;
        
        
        if (data.started !== undefined) updatePayload.started = data.started;
        
        
        if (data.ended !== undefined) updatePayload.ended = data.ended;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.response_cache !== undefined) updatePayload.response_cache = data.response_cache;
        
        
        if (data.progress_percent !== undefined) updatePayload.progress_percent = data.progress_percent;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.survey !== undefined) {
            await fill_sessions.setSurvey(
              
              data.survey,
              
              { transaction }
            );
        }
        
        if (data.ai_model !== undefined) {
            await fill_sessions.setAi_model(
              
              data.ai_model,
              
              { transaction }
            );
        }
        
        if (data.api_key !== undefined) {
            await fill_sessions.setApi_key(
              
              data.api_key,
              
              { transaction }
            );
        }
        

        
        

        

        return fill_sessions;
    }

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

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

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


        return fill_sessions;
    }

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

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

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

        await fill_sessions.destroy({
            transaction
        });

        return fill_sessions;
    }

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

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

        if (!fill_sessions) {
            return fill_sessions;
        }

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

        
        
        
        
        
        
        
        
        
        output.request_queue_session = await fill_sessions.getRequest_queue_session({
            transaction
        });
        
        
        
        
        
        
        output.survey = await fill_sessions.getSurvey({
            transaction
        });
        
        
        output.ai_model = await fill_sessions.getAi_model({
            transaction
        });
        
        
        output.api_key = await fill_sessions.getApi_key({
            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.surveys,
        as: 'survey',
        
        where: filter.survey ? {
          [Op.or]: [
            { id: { [Op.in]: filter.survey.split('|').map(term => Utils.uuid(term)) } },
            {
              title: {
                [Op.or]: filter.survey.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

      {
        model: db.api_keys,
        as: 'api_key',
        
        where: filter.api_key ? {
          [Op.or]: [
            { id: { [Op.in]: filter.api_key.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.api_key.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(
                        'fill_sessions',
                        'session_name',
                        filter.session_name,
                    ),
                };
            }
            
            if (filter.response_cache) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'fill_sessions',
                        'response_cache',
                        filter.response_cache,
                    ),
                };
            }
            

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

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

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

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

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

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

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

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

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

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

        const records = await db.fill_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,
        }));
    }

    
};

