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

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

        const marketplace_apps = await db.marketplace_apps.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
        app_category: data.app_category
        ||
        null
            ,
            
        runtime: data.runtime
        ||
        null
            ,
            
        version: data.version
        ||
        null
            ,
            
        wasm_artifact_uri: data.wasm_artifact_uri
        ||
        null
            ,
            
        reliability_score: data.reliability_score
        ||
        null
            ,
            
        vetting_status: data.vetting_status
        ||
        null
            ,
            
        submitted_at: data.submitted_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await marketplace_apps.setTenant( data.tenant || null, {
            transaction,
        });
        
        await marketplace_apps.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return marketplace_apps;
    }
    

    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 marketplace_appsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                description: item.description
            ||
            null
            ,
            
                app_category: item.app_category
            ||
            null
            ,
            
                runtime: item.runtime
            ||
            null
            ,
            
                version: item.version
            ||
            null
            ,
            
                wasm_artifact_uri: item.wasm_artifact_uri
            ||
            null
            ,
            
                reliability_score: item.reliability_score
            ||
            null
            ,
            
                vetting_status: item.vetting_status
            ||
            null
            ,
            
                submitted_at: item.submitted_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return marketplace_apps;
    }

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        if (data.app_category !== undefined) updatePayload.app_category = data.app_category;
        
        
        if (data.runtime !== undefined) updatePayload.runtime = data.runtime;
        
        
        if (data.version !== undefined) updatePayload.version = data.version;
        
        
        if (data.wasm_artifact_uri !== undefined) updatePayload.wasm_artifact_uri = data.wasm_artifact_uri;
        
        
        if (data.reliability_score !== undefined) updatePayload.reliability_score = data.reliability_score;
        
        
        if (data.vetting_status !== undefined) updatePayload.vetting_status = data.vetting_status;
        
        
        if (data.submitted_at !== undefined) updatePayload.submitted_at = data.submitted_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.tenant !== undefined) {
            await marketplace_apps.setTenant(
              
              data.tenant,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await marketplace_apps.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return marketplace_apps;
    }

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

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

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


        return marketplace_apps;
    }

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

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

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

        await marketplace_apps.destroy({
            transaction
        });

        return marketplace_apps;
    }

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

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

        if (!marketplace_apps) {
            return marketplace_apps;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.app_installations_marketplace_app = await marketplace_apps.getApp_installations_marketplace_app({
            transaction
        });
        
        
        output.app_crash_reports_marketplace_app = await marketplace_apps.getApp_crash_reports_marketplace_app({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        output.tenant = await marketplace_apps.getTenant({
            transaction
        });
        
        
        output.organizations = await marketplace_apps.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.tenants,
        as: 'tenant',
        
        where: filter.tenant ? {
          [Op.or]: [
            { id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.tenant.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.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'marketplace_apps',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'marketplace_apps',
                        'description',
                        filter.description,
                    ),
                };
            }
            
            if (filter.version) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'marketplace_apps',
                        'version',
                        filter.version,
                    ),
                };
            }
            
            if (filter.wasm_artifact_uri) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'marketplace_apps',
                        'wasm_artifact_uri',
                        filter.wasm_artifact_uri,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

            
            if (filter.app_category) {
                where = {
                    ...where,
                app_category: filter.app_category,
            };
            }
            
            if (filter.runtime) {
                where = {
                    ...where,
                runtime: filter.runtime,
            };
            }
            
            if (filter.vetting_status) {
                where = {
                    ...where,
                vetting_status: filter.vetting_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.marketplace_apps.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(
                        'marketplace_apps',
                        'name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

