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

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

        const test_type_schemas = await db.test_type_schemas.create(
            {
                id: data.id || undefined,
        
        test_category: data.test_category
        ||
        null
            ,
            
        test_type: data.test_type
        ||
        null
            ,
            
        display_name_en: data.display_name_en
        ||
        null
            ,
            
        display_name_fr: data.display_name_fr
        ||
        null
            ,
            
        parameters_schema_json: data.parameters_schema_json
        ||
        null
            ,
            
        results_schema_json: data.results_schema_json
        ||
        null
            ,
            
        calculation_rules_json: data.calculation_rules_json
        ||
        null
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await test_type_schemas.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return test_type_schemas;
    }
    

    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 test_type_schemasData = data.map((item, index) => ({
                id: item.id || undefined,
                
                test_category: item.test_category
            ||
            null
            ,
            
                test_type: item.test_type
            ||
            null
            ,
            
                display_name_en: item.display_name_en
            ||
            null
            ,
            
                display_name_fr: item.display_name_fr
            ||
            null
            ,
            
                parameters_schema_json: item.parameters_schema_json
            ||
            null
            ,
            
                results_schema_json: item.results_schema_json
            ||
            null
            ,
            
                calculation_rules_json: item.calculation_rules_json
            ||
            null
            ,
            
                is_active: item.is_active
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return test_type_schemas;
    }

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


        

        const updatePayload = {};
        
        if (data.test_category !== undefined) updatePayload.test_category = data.test_category;
        
        
        if (data.test_type !== undefined) updatePayload.test_type = data.test_type;
        
        
        if (data.display_name_en !== undefined) updatePayload.display_name_en = data.display_name_en;
        
        
        if (data.display_name_fr !== undefined) updatePayload.display_name_fr = data.display_name_fr;
        
        
        if (data.parameters_schema_json !== undefined) updatePayload.parameters_schema_json = data.parameters_schema_json;
        
        
        if (data.results_schema_json !== undefined) updatePayload.results_schema_json = data.results_schema_json;
        
        
        if (data.calculation_rules_json !== undefined) updatePayload.calculation_rules_json = data.calculation_rules_json;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return test_type_schemas;
    }

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

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

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


        return test_type_schemas;
    }

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

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

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

        await test_type_schemas.destroy({
            transaction
        });

        return test_type_schemas;
    }

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

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

        if (!test_type_schemas) {
            return test_type_schemas;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        output.metallurgical_tests_test_type_schema = await test_type_schemas.getMetallurgical_tests_test_type_schema({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.organizations = await test_type_schemas.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.organizations,
        as: 'organizations',
        
      },



    ];

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

            
            if (filter.test_type) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'test_type_schemas',
                        'test_type',
                        filter.test_type,
                    ),
                };
            }
            
            if (filter.display_name_en) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'test_type_schemas',
                        'display_name_en',
                        filter.display_name_en,
                    ),
                };
            }
            
            if (filter.display_name_fr) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'test_type_schemas',
                        'display_name_fr',
                        filter.display_name_fr,
                    ),
                };
            }
            
            if (filter.parameters_schema_json) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'test_type_schemas',
                        'parameters_schema_json',
                        filter.parameters_schema_json,
                    ),
                };
            }
            
            if (filter.results_schema_json) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'test_type_schemas',
                        'results_schema_json',
                        filter.results_schema_json,
                    ),
                };
            }
            
            if (filter.calculation_rules_json) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'test_type_schemas',
                        'calculation_rules_json',
                        filter.calculation_rules_json,
                    ),
                };
            }
            

            
            

            

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

            
            if (filter.test_category) {
                where = {
                    ...where,
                test_category: filter.test_category,
            };
            }
            
            if (filter.is_active) {
                where = {
                    ...where,
                is_active: filter.is_active,
            };
            }
            


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

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

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

    
};

