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

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

        const metallurgical_tests = await db.metallurgical_tests.create(
            {
                id: data.id || undefined,
        
        lab_reference: data.lab_reference
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        date_submitted: data.date_submitted
        ||
        null
            ,
            
        date_completed: data.date_completed
        ||
        null
            ,
            
        data_source: data.data_source
        ||
        null
            ,
            
        parameters_json: data.parameters_json
        ||
        null
            ,
            
        results_json: data.results_json
        ||
        null
            ,
            
        qaqc_status: data.qaqc_status
        ||
        null
            ,
            
        qaqc_notes: data.qaqc_notes
        ||
        null
            ,
            
        reviewed_at: data.reviewed_at
        ||
        null
            ,
            
        approved_at: data.approved_at
        ||
        null
            ,
            
        is_deleted: data.is_deleted
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await metallurgical_tests.setProject( data.project || null, {
            transaction,
        });
        
        await metallurgical_tests.setPhase( data.phase || null, {
            transaction,
        });
        
        await metallurgical_tests.setSample( data.sample || null, {
            transaction,
        });
        
        await metallurgical_tests.setLaboratory( data.laboratory || null, {
            transaction,
        });
        
        await metallurgical_tests.setTest_type_schema( data.test_type_schema || null, {
            transaction,
        });
        
        await metallurgical_tests.setEntered_by( data.entered_by || null, {
            transaction,
        });
        
        await metallurgical_tests.setReviewed_by( data.reviewed_by || null, {
            transaction,
        });
        
        await metallurgical_tests.setApproved_by( data.approved_by || null, {
            transaction,
        });
        
        await metallurgical_tests.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return metallurgical_tests;
    }
    

    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 metallurgical_testsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                lab_reference: item.lab_reference
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                date_submitted: item.date_submitted
            ||
            null
            ,
            
                date_completed: item.date_completed
            ||
            null
            ,
            
                data_source: item.data_source
            ||
            null
            ,
            
                parameters_json: item.parameters_json
            ||
            null
            ,
            
                results_json: item.results_json
            ||
            null
            ,
            
                qaqc_status: item.qaqc_status
            ||
            null
            ,
            
                qaqc_notes: item.qaqc_notes
            ||
            null
            ,
            
                reviewed_at: item.reviewed_at
            ||
            null
            ,
            
                approved_at: item.approved_at
            ||
            null
            ,
            
                is_deleted: item.is_deleted
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return metallurgical_tests;
    }

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


        

        const updatePayload = {};
        
        if (data.lab_reference !== undefined) updatePayload.lab_reference = data.lab_reference;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.date_submitted !== undefined) updatePayload.date_submitted = data.date_submitted;
        
        
        if (data.date_completed !== undefined) updatePayload.date_completed = data.date_completed;
        
        
        if (data.data_source !== undefined) updatePayload.data_source = data.data_source;
        
        
        if (data.parameters_json !== undefined) updatePayload.parameters_json = data.parameters_json;
        
        
        if (data.results_json !== undefined) updatePayload.results_json = data.results_json;
        
        
        if (data.qaqc_status !== undefined) updatePayload.qaqc_status = data.qaqc_status;
        
        
        if (data.qaqc_notes !== undefined) updatePayload.qaqc_notes = data.qaqc_notes;
        
        
        if (data.reviewed_at !== undefined) updatePayload.reviewed_at = data.reviewed_at;
        
        
        if (data.approved_at !== undefined) updatePayload.approved_at = data.approved_at;
        
        
        if (data.is_deleted !== undefined) updatePayload.is_deleted = data.is_deleted;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.project !== undefined) {
            await metallurgical_tests.setProject(
              
              data.project,
              
              { transaction }
            );
        }
        
        if (data.phase !== undefined) {
            await metallurgical_tests.setPhase(
              
              data.phase,
              
              { transaction }
            );
        }
        
        if (data.sample !== undefined) {
            await metallurgical_tests.setSample(
              
              data.sample,
              
              { transaction }
            );
        }
        
        if (data.laboratory !== undefined) {
            await metallurgical_tests.setLaboratory(
              
              data.laboratory,
              
              { transaction }
            );
        }
        
        if (data.test_type_schema !== undefined) {
            await metallurgical_tests.setTest_type_schema(
              
              data.test_type_schema,
              
              { transaction }
            );
        }
        
        if (data.entered_by !== undefined) {
            await metallurgical_tests.setEntered_by(
              
              data.entered_by,
              
              { transaction }
            );
        }
        
        if (data.reviewed_by !== undefined) {
            await metallurgical_tests.setReviewed_by(
              
              data.reviewed_by,
              
              { transaction }
            );
        }
        
        if (data.approved_by !== undefined) {
            await metallurgical_tests.setApproved_by(
              
              data.approved_by,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await metallurgical_tests.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return metallurgical_tests;
    }

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

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

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


        return metallurgical_tests;
    }

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

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

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

        await metallurgical_tests.destroy({
            transaction
        });

        return metallurgical_tests;
    }

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

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

        if (!metallurgical_tests) {
            return metallurgical_tests;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.test_result_points_metallurgical_test = await metallurgical_tests.getTest_result_points_metallurgical_test({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.project = await metallurgical_tests.getProject({
            transaction
        });
        
        
        output.phase = await metallurgical_tests.getPhase({
            transaction
        });
        
        
        output.sample = await metallurgical_tests.getSample({
            transaction
        });
        
        
        output.laboratory = await metallurgical_tests.getLaboratory({
            transaction
        });
        
        
        output.test_type_schema = await metallurgical_tests.getTest_type_schema({
            transaction
        });
        
        
        output.entered_by = await metallurgical_tests.getEntered_by({
            transaction
        });
        
        
        output.reviewed_by = await metallurgical_tests.getReviewed_by({
            transaction
        });
        
        
        output.approved_by = await metallurgical_tests.getApproved_by({
            transaction
        });
        
        
        output.organizations = await metallurgical_tests.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.projects,
        as: 'project',
        
        where: filter.project ? {
          [Op.or]: [
            { id: { [Op.in]: filter.project.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.project.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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

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

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

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

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

      {
        model: db.users,
        as: 'approved_by',
        
        where: filter.approved_by ? {
          [Op.or]: [
            { id: { [Op.in]: filter.approved_by.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.approved_by.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.lab_reference) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'metallurgical_tests',
                        'lab_reference',
                        filter.lab_reference,
                    ),
                };
            }
            
            if (filter.parameters_json) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'metallurgical_tests',
                        'parameters_json',
                        filter.parameters_json,
                    ),
                };
            }
            
            if (filter.results_json) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'metallurgical_tests',
                        'results_json',
                        filter.results_json,
                    ),
                };
            }
            
            if (filter.qaqc_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'metallurgical_tests',
                        'qaqc_notes',
                        filter.qaqc_notes,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

            
            if (filter.status) {
                where = {
                    ...where,
                status: filter.status,
            };
            }
            
            if (filter.data_source) {
                where = {
                    ...where,
                data_source: filter.data_source,
            };
            }
            
            if (filter.qaqc_status) {
                where = {
                    ...where,
                qaqc_status: filter.qaqc_status,
            };
            }
            
            if (filter.is_deleted) {
                where = {
                    ...where,
                is_deleted: filter.is_deleted,
            };
            }
            


      

      

      

      

      

      

      

      

      
      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.metallurgical_tests.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(
                        'metallurgical_tests',
                        'lab_reference',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

