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

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

        const design_criteria_items = await db.design_criteria_items.create(
            {
                id: data.id || undefined,
        
        parameter: data.parameter
        ||
        null
            ,
            
        value: data.value
        ||
        null
            ,
            
        unit: data.unit
        ||
        null
            ,
            
        confidence: data.confidence
        ||
        null
            ,
            
        basis_notes: data.basis_notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await design_criteria_items.setProject( data.project || null, {
            transaction,
        });
        
        await design_criteria_items.setPhase( data.phase || null, {
            transaction,
        });
        
        await design_criteria_items.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        
        await design_criteria_items.setSource_tests(data.source_tests || [], {
            transaction,
        });
        

        

        return design_criteria_items;
    }
    

    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 design_criteria_itemsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                parameter: item.parameter
            ||
            null
            ,
            
                value: item.value
            ||
            null
            ,
            
                unit: item.unit
            ||
            null
            ,
            
                confidence: item.confidence
            ||
            null
            ,
            
                basis_notes: item.basis_notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return design_criteria_items;
    }

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


        

        const updatePayload = {};
        
        if (data.parameter !== undefined) updatePayload.parameter = data.parameter;
        
        
        if (data.value !== undefined) updatePayload.value = data.value;
        
        
        if (data.unit !== undefined) updatePayload.unit = data.unit;
        
        
        if (data.confidence !== undefined) updatePayload.confidence = data.confidence;
        
        
        if (data.basis_notes !== undefined) updatePayload.basis_notes = data.basis_notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.project !== undefined) {
            await design_criteria_items.setProject(
              
              data.project,
              
              { transaction }
            );
        }
        
        if (data.phase !== undefined) {
            await design_criteria_items.setPhase(
              
              data.phase,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await design_criteria_items.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        
        if (data.source_tests !== undefined) {
            await design_criteria_items.setSource_tests(data.source_tests, { transaction });
        }
        

        

        return design_criteria_items;
    }

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

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

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


        return design_criteria_items;
    }

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

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

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

        await design_criteria_items.destroy({
            transaction
        });

        return design_criteria_items;
    }

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

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

        if (!design_criteria_items) {
            return design_criteria_items;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.project = await design_criteria_items.getProject({
            transaction
        });
        
        
        output.phase = await design_criteria_items.getPhase({
            transaction
        });
        
        
        output.source_tests = await design_criteria_items.getSource_tests({
            transaction
        });
        
        
        output.organizations = await design_criteria_items.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.organizations,
        as: 'organizations',
        
      },


      {
        model: db.metallurgical_tests,
        as: 'source_tests',
        required: false,
      },


    ];

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

            
            if (filter.parameter) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'design_criteria_items',
                        'parameter',
                        filter.parameter,
                    ),
                };
            }
            
            if (filter.unit) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'design_criteria_items',
                        'unit',
                        filter.unit,
                    ),
                };
            }
            
            if (filter.basis_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'design_criteria_items',
                        'basis_notes',
                        filter.basis_notes,
                    ),
                };
            }
            

            
            

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

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

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

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

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


      

      

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

        where = {
          ...where,
          organizationsId: {[Op.or]: listItems}
        };
      }
      


      if (filter.source_tests) {
        const searchTerms = filter.source_tests.split('|');

        include = [
          {
            model: db.metallurgical_tests,
            as: 'source_tests_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  lab_reference: {
                    [Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
                  }
                }
              ]
            } : undefined
          },
          ...include,
        ]
      }


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

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

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

    
};

