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

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

        const supplier_diligence_checks = await db.supplier_diligence_checks.create(
            {
                id: data.id || undefined,
        
        check_type: data.check_type
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
        checked_at: data.checked_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await supplier_diligence_checks.setTenant( data.tenant || null, {
            transaction,
        });
        
        await supplier_diligence_checks.setSupplier( data.supplier || null, {
            transaction,
        });
        
        await supplier_diligence_checks.setChecked_by( data.checked_by || null, {
            transaction,
        });
        
        await supplier_diligence_checks.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

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

        return supplier_diligence_checks;
    }
    

    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 supplier_diligence_checksData = data.map((item, index) => ({
                id: item.id || undefined,
                
                check_type: item.check_type
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                notes: item.notes
            ||
            null
            ,
            
                checked_at: item.checked_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return supplier_diligence_checks;
    }

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


        

        const updatePayload = {};
        
        if (data.check_type !== undefined) updatePayload.check_type = data.check_type;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        if (data.checked_at !== undefined) updatePayload.checked_at = data.checked_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.tenant !== undefined) {
            await supplier_diligence_checks.setTenant(
              
              data.tenant,
              
              { transaction }
            );
        }
        
        if (data.supplier !== undefined) {
            await supplier_diligence_checks.setSupplier(
              
              data.supplier,
              
              { transaction }
            );
        }
        
        if (data.checked_by !== undefined) {
            await supplier_diligence_checks.setChecked_by(
              
              data.checked_by,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await supplier_diligence_checks.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

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

        return supplier_diligence_checks;
    }

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

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

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


        return supplier_diligence_checks;
    }

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

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

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

        await supplier_diligence_checks.destroy({
            transaction
        });

        return supplier_diligence_checks;
    }

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

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

        if (!supplier_diligence_checks) {
            return supplier_diligence_checks;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.tenant = await supplier_diligence_checks.getTenant({
            transaction
        });
        
        
        output.supplier = await supplier_diligence_checks.getSupplier({
            transaction
        });
        
        
        output.evidence_files = await supplier_diligence_checks.getEvidence_files({
            transaction
        });
        
        
        output.checked_by = await supplier_diligence_checks.getChecked_by({
            transaction
        });
        
        
        output.organizations = await supplier_diligence_checks.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.suppliers,
        as: 'supplier',
        
        where: filter.supplier ? {
          [Op.or]: [
            { id: { [Op.in]: filter.supplier.split('|').map(term => Utils.uuid(term)) } },
            {
              legal_name: {
                [Op.or]: filter.supplier.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.users,
        as: 'checked_by',
        
        where: filter.checked_by ? {
          [Op.or]: [
            { id: { [Op.in]: filter.checked_by.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.checked_by.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



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

    ];

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

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

            
            

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

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

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

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

            
            if (filter.check_type) {
                where = {
                    ...where,
                check_type: filter.check_type,
            };
            }
            
            if (filter.status) {
                where = {
                    ...where,
                status: filter.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.supplier_diligence_checks.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(
                        'supplier_diligence_checks',
                        'check_type',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

