
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const TenantAccess = require('./tenantAccess');



const Sequelize = db.Sequelize;
const Op = Sequelize.Op;

module.exports = class Sampled_subjectsDBApi {
    

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

        const sampled_subjects = await db.sampled_subjects.create(
            {
                id: data.id || undefined,
        
        sample_type: data.sample_type
        ||
        null
            ,
            
        display_name: data.display_name
        ||
        null
            ,
            
        identifier: data.identifier
        ||
        null
            ,
            
        department: data.department
        ||
        null
            ,
            
        role_name: data.role_name
        ||
        null
            ,
            
        manager: data.manager
        ||
        null
            ,
            
        event_date: data.event_date
        ||
        null
            ,
            
        risk_tier: data.risk_tier
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await sampled_subjects.setOrganization(currentUser.organization.id || null, {
            transaction,
        });
        
        await sampled_subjects.setWorkflow( data.workflow || null, {
            transaction,
        });
        

        

        

        return sampled_subjects;
    }
    

    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 sampled_subjectsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                sample_type: item.sample_type
            ||
            null
            ,
            
                display_name: item.display_name
            ||
            null
            ,
            
                identifier: item.identifier
            ||
            null
            ,
            
                department: item.department
            ||
            null
            ,
            
                role_name: item.role_name
            ||
            null
            ,
            
                manager: item.manager
            ||
            null
            ,
            
                event_date: item.event_date
            ||
            null
            ,
            
                risk_tier: item.risk_tier
            ||
            null
            ,
            
                status: item.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 sampled_subjects = await db.sampled_subjects.bulkCreate(sampled_subjectsData, { transaction });

        // For each item created, replace relation files
        

        return sampled_subjects;
    }

    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 sampled_subjects = await TenantAccess.findByPkOrThrow(db.sampled_subjects, id, options);


        

        const updatePayload = {};
        
        if (data.sample_type !== undefined) updatePayload.sample_type = data.sample_type;
        
        
        if (data.display_name !== undefined) updatePayload.display_name = data.display_name;
        
        
        if (data.identifier !== undefined) updatePayload.identifier = data.identifier;
        
        
        if (data.department !== undefined) updatePayload.department = data.department;
        
        
        if (data.role_name !== undefined) updatePayload.role_name = data.role_name;
        
        
        if (data.manager !== undefined) updatePayload.manager = data.manager;
        
        
        if (data.event_date !== undefined) updatePayload.event_date = data.event_date;
        
        
        if (data.risk_tier !== undefined) updatePayload.risk_tier = data.risk_tier;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.organization !== undefined) {
            await sampled_subjects.setOrganization(
              
              (globalAccess ? data.organization : currentUser.organization.id),
              
              { transaction }
            );
        }
        
        if (data.workflow !== undefined) {
            await sampled_subjects.setWorkflow(
              
              data.workflow,
              
              { transaction }
            );
        }
        

        
        

        

        return sampled_subjects;
    }

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

        const sampled_subjects = await TenantAccess.findAllByIds(db.sampled_subjects, ids, options);

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


        return sampled_subjects;
    }

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

        const sampled_subjects = await TenantAccess.findByPkOrThrow(db.sampled_subjects, id, options);

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

        await sampled_subjects.destroy({
            transaction
        });

        return sampled_subjects;
    }

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

        const sampled_subjects = await TenantAccess.findOne(db.sampled_subjects, where, options);

        if (!sampled_subjects) {
            return sampled_subjects;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        output.proof_packets_sampled_subject = await sampled_subjects.getProof_packets_sampled_subject({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        output.organization = await sampled_subjects.getOrganization({
            transaction
        });
        
        
        output.workflow = await sampled_subjects.getWorkflow({
            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.organizations,
        as: 'organization',
        
      },

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



    ];

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

            
            if (filter.display_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'sampled_subjects',
                        'display_name',
                        filter.display_name,
                    ),
                };
            }
            
            if (filter.identifier) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'sampled_subjects',
                        'identifier',
                        filter.identifier,
                    ),
                };
            }
            
            if (filter.department) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'sampled_subjects',
                        'department',
                        filter.department,
                    ),
                };
            }
            
            if (filter.role_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'sampled_subjects',
                        'role_name',
                        filter.role_name,
                    ),
                };
            }
            
            if (filter.manager) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'sampled_subjects',
                        'manager',
                        filter.manager,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'sampled_subjects',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

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

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

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

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

            
            if (filter.sample_type) {
                where = {
                    ...where,
                sample_type: filter.sample_type,
            };
            }
            
            if (filter.risk_tier) {
                where = {
                    ...where,
                risk_tier: filter.risk_tier,
            };
            }
            
            if (filter.status) {
                where = {
                    ...where,
                status: filter.status,
            };
            }
            


      
      if (filter.organization) {
        const listItems = filter.organization.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          organizationId: {[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.sampled_subjects.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(
                        'sampled_subjects',
                        'display_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

