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

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

        const code_snippets = await db.code_snippets.create(
            {
                id: data.id || undefined,
        
        title: data.title
        ||
        null
            ,
            
        language: data.language
        ||
        null
            ,
            
        code: data.code
        ||
        null
            ,
            
        entry_point: data.entry_point
        ||
        null
            ,
            
        is_runnable: data.is_runnable
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await code_snippets.setWorkspace( data.workspace || null, {
            transaction,
        });
        
        await code_snippets.setAuthor( data.author || null, {
            transaction,
        });
        
        await code_snippets.setMessage( data.message || null, {
            transaction,
        });
        
        await code_snippets.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return code_snippets;
    }
    

    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 code_snippetsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                title: item.title
            ||
            null
            ,
            
                language: item.language
            ||
            null
            ,
            
                code: item.code
            ||
            null
            ,
            
                entry_point: item.entry_point
            ||
            null
            ,
            
                is_runnable: item.is_runnable
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return code_snippets;
    }

    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 code_snippets = await db.code_snippets.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.title !== undefined) updatePayload.title = data.title;
        
        
        if (data.language !== undefined) updatePayload.language = data.language;
        
        
        if (data.code !== undefined) updatePayload.code = data.code;
        
        
        if (data.entry_point !== undefined) updatePayload.entry_point = data.entry_point;
        
        
        if (data.is_runnable !== undefined) updatePayload.is_runnable = data.is_runnable;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.workspace !== undefined) {
            await code_snippets.setWorkspace(
              
              data.workspace,
              
              { transaction }
            );
        }
        
        if (data.author !== undefined) {
            await code_snippets.setAuthor(
              
              data.author,
              
              { transaction }
            );
        }
        
        if (data.message !== undefined) {
            await code_snippets.setMessage(
              
              data.message,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await code_snippets.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return code_snippets;
    }

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

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

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


        return code_snippets;
    }

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

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

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

        await code_snippets.destroy({
            transaction
        });

        return code_snippets;
    }

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

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

        if (!code_snippets) {
            return code_snippets;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.executions_snippet = await code_snippets.getExecutions_snippet({
            transaction
        });
        
        
        output.debug_sessions_snippet = await code_snippets.getDebug_sessions_snippet({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        output.workspace = await code_snippets.getWorkspace({
            transaction
        });
        
        
        output.author = await code_snippets.getAuthor({
            transaction
        });
        
        
        output.message = await code_snippets.getMessage({
            transaction
        });
        
        
        output.organizations = await code_snippets.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.users,
        as: 'author',
        
        where: filter.author ? {
          [Op.or]: [
            { id: { [Op.in]: filter.author.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.author.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.messages,
        as: 'message',
        
        where: filter.message ? {
          [Op.or]: [
            { id: { [Op.in]: filter.message.split('|').map(term => Utils.uuid(term)) } },
            {
              content: {
                [Op.or]: filter.message.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.title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'code_snippets',
                        'title',
                        filter.title,
                    ),
                };
            }
            
            if (filter.code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'code_snippets',
                        'code',
                        filter.code,
                    ),
                };
            }
            
            if (filter.entry_point) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'code_snippets',
                        'entry_point',
                        filter.entry_point,
                    ),
                };
            }
            

            
            

            

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

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


      

      

      

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

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

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

    
};

