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

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

        const build_artifacts = await db.build_artifacts.create(
            {
                id: data.id || undefined,
        
        artifact_type: data.artifact_type
        ||
        null
            ,
            
        file_name: data.file_name
        ||
        null
            ,
            
        download_url: data.download_url
        ||
        null
            ,
            
        checksum_sha256: data.checksum_sha256
        ||
        null
            ,
            
        generated_at: data.generated_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await build_artifacts.setBuild_job( data.build_job || null, {
            transaction,
        });
        
        await build_artifacts.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

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

        return build_artifacts;
    }
    

    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 build_artifactsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                artifact_type: item.artifact_type
            ||
            null
            ,
            
                file_name: item.file_name
            ||
            null
            ,
            
                download_url: item.download_url
            ||
            null
            ,
            
                checksum_sha256: item.checksum_sha256
            ||
            null
            ,
            
                generated_at: item.generated_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return build_artifacts;
    }

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


        

        const updatePayload = {};
        
        if (data.artifact_type !== undefined) updatePayload.artifact_type = data.artifact_type;
        
        
        if (data.file_name !== undefined) updatePayload.file_name = data.file_name;
        
        
        if (data.download_url !== undefined) updatePayload.download_url = data.download_url;
        
        
        if (data.checksum_sha256 !== undefined) updatePayload.checksum_sha256 = data.checksum_sha256;
        
        
        if (data.generated_at !== undefined) updatePayload.generated_at = data.generated_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.build_job !== undefined) {
            await build_artifacts.setBuild_job(
              
              data.build_job,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await build_artifacts.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

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

        return build_artifacts;
    }

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

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

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


        return build_artifacts;
    }

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

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

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

        await build_artifacts.destroy({
            transaction
        });

        return build_artifacts;
    }

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

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

        if (!build_artifacts) {
            return build_artifacts;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.build_job = await build_artifacts.getBuild_job({
            transaction
        });
        
        
        output.file_blob = await build_artifacts.getFile_blob({
            transaction
        });
        
        
        output.organizations = await build_artifacts.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.build_jobs,
        as: 'build_job',
        
        where: filter.build_job ? {
          [Op.or]: [
            { id: { [Op.in]: filter.build_job.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.build_job.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



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

    ];

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

            
            if (filter.file_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'build_artifacts',
                        'file_name',
                        filter.file_name,
                    ),
                };
            }
            
            if (filter.download_url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'build_artifacts',
                        'download_url',
                        filter.download_url,
                    ),
                };
            }
            
            if (filter.checksum_sha256) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'build_artifacts',
                        'checksum_sha256',
                        filter.checksum_sha256,
                    ),
                };
            }
            

            
            

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

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

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

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

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


      

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

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

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

    
};

