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

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

        const user_credentials = await db.user_credentials.create(
            {
                id: data.id || undefined,
        
        credential_type: data.credential_type
        ||
        null
            ,
            
        title_text: data.title_text
        ||
        null
            ,
            
        issuer_name: data.issuer_name
        ||
        null
            ,
            
        issued_at: data.issued_at
        ||
        null
            ,
            
        valid_until: data.valid_until
        ||
        null
            ,
            
        verification_status: data.verification_status
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await user_credentials.setUser( data.user || null, {
            transaction,
        });
        
        await user_credentials.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

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

        return user_credentials;
    }
    

    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 user_credentialsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                credential_type: item.credential_type
            ||
            null
            ,
            
                title_text: item.title_text
            ||
            null
            ,
            
                issuer_name: item.issuer_name
            ||
            null
            ,
            
                issued_at: item.issued_at
            ||
            null
            ,
            
                valid_until: item.valid_until
            ||
            null
            ,
            
                verification_status: item.verification_status
            ||
            null
            ,
            
                notes: item.notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return user_credentials;
    }

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


        

        const updatePayload = {};
        
        if (data.credential_type !== undefined) updatePayload.credential_type = data.credential_type;
        
        
        if (data.title_text !== undefined) updatePayload.title_text = data.title_text;
        
        
        if (data.issuer_name !== undefined) updatePayload.issuer_name = data.issuer_name;
        
        
        if (data.issued_at !== undefined) updatePayload.issued_at = data.issued_at;
        
        
        if (data.valid_until !== undefined) updatePayload.valid_until = data.valid_until;
        
        
        if (data.verification_status !== undefined) updatePayload.verification_status = data.verification_status;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.user !== undefined) {
            await user_credentials.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await user_credentials.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

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

        return user_credentials;
    }

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

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

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


        return user_credentials;
    }

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

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

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

        await user_credentials.destroy({
            transaction
        });

        return user_credentials;
    }

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

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

        if (!user_credentials) {
            return user_credentials;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await user_credentials.getUser({
            transaction
        });
        
        
        output.proof_files = await user_credentials.getProof_files({
            transaction
        });
        
        
        output.organizations = await user_credentials.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.users,
        as: 'user',
        
        where: filter.user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



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

    ];

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

            
            if (filter.title_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'user_credentials',
                        'title_text',
                        filter.title_text,
                    ),
                };
            }
            
            if (filter.issuer_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'user_credentials',
                        'issuer_name',
                        filter.issuer_name,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'user_credentials',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

            
            if (filter.credential_type) {
                where = {
                    ...where,
                credential_type: filter.credential_type,
            };
            }
            
            if (filter.verification_status) {
                where = {
                    ...where,
                verification_status: filter.verification_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.user_credentials.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(
                        'user_credentials',
                        'title_text',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

