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

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

        const identity_providers = await db.identity_providers.create(
            {
                id: data.id || undefined,
        
        provider_type: data.provider_type
        ||
        null
            ,
            
        name: data.name
        ||
        null
            ,
            
        issuer_url: data.issuer_url
        ||
        null
            ,
            
        client_id: data.client_id
        ||
        null
            ,
            
        sso_metadata_url: data.sso_metadata_url
        ||
        null
            ,
            
        jit_provisioning_enabled: data.jit_provisioning_enabled
        ||
        false
        
            ,
            
        scim_enabled: data.scim_enabled
        ||
        false
        
            ,
            
        idp_status: data.idp_status
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

        

        return identity_providers;
    }
    

    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 identity_providersData = data.map((item, index) => ({
                id: item.id || undefined,
                
                provider_type: item.provider_type
            ||
            null
            ,
            
                name: item.name
            ||
            null
            ,
            
                issuer_url: item.issuer_url
            ||
            null
            ,
            
                client_id: item.client_id
            ||
            null
            ,
            
                sso_metadata_url: item.sso_metadata_url
            ||
            null
            ,
            
                jit_provisioning_enabled: item.jit_provisioning_enabled
            ||
            false
        
            ,
            
                scim_enabled: item.scim_enabled
            ||
            false
        
            ,
            
                idp_status: item.idp_status
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return identity_providers;
    }

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


        

        const updatePayload = {};
        
        if (data.provider_type !== undefined) updatePayload.provider_type = data.provider_type;
        
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.issuer_url !== undefined) updatePayload.issuer_url = data.issuer_url;
        
        
        if (data.client_id !== undefined) updatePayload.client_id = data.client_id;
        
        
        if (data.sso_metadata_url !== undefined) updatePayload.sso_metadata_url = data.sso_metadata_url;
        
        
        if (data.jit_provisioning_enabled !== undefined) updatePayload.jit_provisioning_enabled = data.jit_provisioning_enabled;
        
        
        if (data.scim_enabled !== undefined) updatePayload.scim_enabled = data.scim_enabled;
        
        
        if (data.idp_status !== undefined) updatePayload.idp_status = data.idp_status;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return identity_providers;
    }

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

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

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


        return identity_providers;
    }

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

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

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

        await identity_providers.destroy({
            transaction
        });

        return identity_providers;
    }

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

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

        if (!identity_providers) {
            return identity_providers;
        }

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

        
        
        
        
        
        
        
        
        
        
        output.user_identities_identity_provider = await identity_providers.getUser_identities_identity_provider({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.tenant = await identity_providers.getTenant({
            transaction
        });
        
        
        output.organizations = await identity_providers.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(
                        'identity_providers',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.issuer_url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'identity_providers',
                        'issuer_url',
                        filter.issuer_url,
                    ),
                };
            }
            
            if (filter.client_id) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'identity_providers',
                        'client_id',
                        filter.client_id,
                    ),
                };
            }
            
            if (filter.sso_metadata_url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'identity_providers',
                        'sso_metadata_url',
                        filter.sso_metadata_url,
                    ),
                };
            }
            

            
            

            

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

            
            if (filter.provider_type) {
                where = {
                    ...where,
                provider_type: filter.provider_type,
            };
            }
            
            if (filter.jit_provisioning_enabled) {
                where = {
                    ...where,
                jit_provisioning_enabled: filter.jit_provisioning_enabled,
            };
            }
            
            if (filter.scim_enabled) {
                where = {
                    ...where,
                scim_enabled: filter.scim_enabled,
            };
            }
            
            if (filter.idp_status) {
                where = {
                    ...where,
                idp_status: filter.idp_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.identity_providers.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(
                        'identity_providers',
                        'name',
                        query,
                    ),
                ],
            };
        }

        const records = await db.identity_providers.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,
        }));
    }

    
};

