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

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

        const debug_sessions = await db.debug_sessions.create(
            {
                id: data.id || undefined,
        
        status: data.status
        ||
        null
            ,
            
        error_summary: data.error_summary
        ||
        null
            ,
            
        error_details: data.error_details
        ||
        null
            ,
            
        opened_at: data.opened_at
        ||
        null
            ,
            
        closed_at: data.closed_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await debug_sessions.setWorkspace( data.workspace || null, {
            transaction,
        });
        
        await debug_sessions.setSnippet( data.snippet || null, {
            transaction,
        });
        
        await debug_sessions.setStarted_by( data.started_by || null, {
            transaction,
        });
        
        await debug_sessions.setAssigned_agent( data.assigned_agent || null, {
            transaction,
        });
        
        await debug_sessions.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return debug_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 debug_sessionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                status: item.status
            ||
            null
            ,
            
                error_summary: item.error_summary
            ||
            null
            ,
            
                error_details: item.error_details
            ||
            null
            ,
            
                opened_at: item.opened_at
            ||
            null
            ,
            
                closed_at: item.closed_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return debug_sessions;
    }

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

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


        

        const updatePayload = {};
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.error_summary !== undefined) updatePayload.error_summary = data.error_summary;
        
        
        if (data.error_details !== undefined) updatePayload.error_details = data.error_details;
        
        
        if (data.opened_at !== undefined) updatePayload.opened_at = data.opened_at;
        
        
        if (data.closed_at !== undefined) updatePayload.closed_at = data.closed_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.workspace !== undefined) {
            await debug_sessions.setWorkspace(
              
              data.workspace,
              
              { transaction }
            );
        }
        
        if (data.snippet !== undefined) {
            await debug_sessions.setSnippet(
              
              data.snippet,
              
              { transaction }
            );
        }
        
        if (data.started_by !== undefined) {
            await debug_sessions.setStarted_by(
              
              data.started_by,
              
              { transaction }
            );
        }
        
        if (data.assigned_agent !== undefined) {
            await debug_sessions.setAssigned_agent(
              
              data.assigned_agent,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await debug_sessions.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return debug_sessions;
    }

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

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

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


        return debug_sessions;
    }

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

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

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

        await debug_sessions.destroy({
            transaction
        });

        return debug_sessions;
    }

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

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

        if (!debug_sessions) {
            return debug_sessions;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.debug_fixes_debug_session = await debug_sessions.getDebug_fixes_debug_session({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        output.workspace = await debug_sessions.getWorkspace({
            transaction
        });
        
        
        output.snippet = await debug_sessions.getSnippet({
            transaction
        });
        
        
        output.started_by = await debug_sessions.getStarted_by({
            transaction
        });
        
        
        output.assigned_agent = await debug_sessions.getAssigned_agent({
            transaction
        });
        
        
        output.organizations = await debug_sessions.getOrganizations({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           globalAccess,  options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        
        const user = (options && options.currentUser) || null;
        const userOrganizations = (user && user.organizations?.id) || null;
        

        
        if (userOrganizations) {
            if (options?.currentUser?.organizationsId) {
                where.organizationsId = options.currentUser.organizationsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

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

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

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

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

      {
        model: db.organizations,
        as: 'organizations',
        
      },



    ];

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

            
            if (filter.error_summary) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'debug_sessions',
                        'error_summary',
                        filter.error_summary,
                    ),
                };
            }
            
            if (filter.error_details) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'debug_sessions',
                        'error_details',
                        filter.error_details,
                    ),
                };
            }
            

            
            

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    closed_at: {
                    ...where.closed_at,
                            [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.organizations) {
        const listItems = filter.organizations.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          organizationsId: {[Op.or]: listItems}
        };
      }
      



            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,
                        },
                    };
                }
            }
        }
        

        
        if (globalAccess) {
            delete where.organizationsId;
        }
        

        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.debug_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,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'debug_sessions',
                        'error_summary',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

