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

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

        const code_files = await db.code_files.create(
            {
                id: data.id || undefined,
        
        path: data.path
        ||
        null
            ,
            
        language: data.language
        ||
        null
            ,
            
        content: data.content
        ||
        null
            ,
            
        content_hash: data.content_hash
        ||
        null
            ,
            
        last_modified_at: data.last_modified_at
        ||
        null
            ,
            
        is_binary: data.is_binary
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await code_files.setRepository( data.repository || null, {
            transaction,
        });
        
        await code_files.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.code_files.getTableName(),
                belongsToColumn: 'binary_blob',
                belongsToId: code_files.id,
            },
            data.binary_blob,
            options,
        );
        

        return code_files;
    }
    

    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_filesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                path: item.path
            ||
            null
            ,
            
                language: item.language
            ||
            null
            ,
            
                content: item.content
            ||
            null
            ,
            
                content_hash: item.content_hash
            ||
            null
            ,
            
                last_modified_at: item.last_modified_at
            ||
            null
            ,
            
                is_binary: item.is_binary
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        
        for (let i = 0; i < code_files.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.code_files.getTableName(),
                    belongsToColumn: 'binary_blob',
                    belongsToId: code_files[i].id,
                },
                data[i].binary_blob,
                options,
            );
        }
        

        return code_files;
    }

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


        

        const updatePayload = {};
        
        if (data.path !== undefined) updatePayload.path = data.path;
        
        
        if (data.language !== undefined) updatePayload.language = data.language;
        
        
        if (data.content !== undefined) updatePayload.content = data.content;
        
        
        if (data.content_hash !== undefined) updatePayload.content_hash = data.content_hash;
        
        
        if (data.last_modified_at !== undefined) updatePayload.last_modified_at = data.last_modified_at;
        
        
        if (data.is_binary !== undefined) updatePayload.is_binary = data.is_binary;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.repository !== undefined) {
            await code_files.setRepository(
              
              data.repository,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await code_files.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.code_files.getTableName(),
                belongsToColumn: 'binary_blob',
                belongsToId: code_files.id,
            },
            data.binary_blob,
            options,
        );
        

        return code_files;
    }

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

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

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


        return code_files;
    }

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

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

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

        await code_files.destroy({
            transaction
        });

        return code_files;
    }

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

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

        if (!code_files) {
            return code_files;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.repository = await code_files.getRepository({
            transaction
        });
        
        
        output.binary_blob = await code_files.getBinary_blob({
            transaction
        });
        
        
        output.organizations = await code_files.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.code_repositories,
        as: 'repository',
        
        where: filter.repository ? {
          [Op.or]: [
            { id: { [Op.in]: filter.repository.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.repository.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



      {
        model: db.file,
        as: 'binary_blob',
      },

    ];

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

            
            if (filter.path) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'code_files',
                        'path',
                        filter.path,
                    ),
                };
            }
            
            if (filter.language) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'code_files',
                        'language',
                        filter.language,
                    ),
                };
            }
            
            if (filter.content) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'code_files',
                        'content',
                        filter.content,
                    ),
                };
            }
            
            if (filter.content_hash) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'code_files',
                        'content_hash',
                        filter.content_hash,
                    ),
                };
            }
            

            
            

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

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

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

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

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


      

      
      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_files.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_files',
                        'path',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

