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

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

        const quality_standards = await db.quality_standards.create(
            {
                id: data.id || undefined,
        
        standard_name: data.standard_name
        ||
        null
            ,
            
        standard_code: data.standard_code
        ||
        null
            ,
            
        inspection_type: data.inspection_type
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        requirements: data.requirements
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await quality_standards.setMaterial( data.material || null, {
            transaction,
        });
        
        await quality_standards.setRevision( data.revision || null, {
            transaction,
        });
        

        

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

        return quality_standards;
    }
    

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

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

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

        return quality_standards;
    }

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

        const quality_standards = await db.quality_standards.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.standard_name !== undefined) updatePayload.standard_name = data.standard_name;
        
        
        if (data.standard_code !== undefined) updatePayload.standard_code = data.standard_code;
        
        
        if (data.inspection_type !== undefined) updatePayload.inspection_type = data.inspection_type;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.requirements !== undefined) updatePayload.requirements = data.requirements;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.material !== undefined) {
            await quality_standards.setMaterial(
              
              data.material,
              
              { transaction }
            );
        }
        
        if (data.revision !== undefined) {
            await quality_standards.setRevision(
              
              data.revision,
              
              { transaction }
            );
        }
        

        
        

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

        return quality_standards;
    }

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

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

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


        return quality_standards;
    }

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

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

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

        await quality_standards.destroy({
            transaction
        });

        return quality_standards;
    }

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

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

        if (!quality_standards) {
            return quality_standards;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.inspection_plans_quality_standard = await quality_standards.getInspection_plans_quality_standard({
            transaction
        });
        
        
        
        
        
        
        
        
        output.material = await quality_standards.getMaterial({
            transaction
        });
        
        
        output.revision = await quality_standards.getRevision({
            transaction
        });
        
        
        output.attachments = await quality_standards.getAttachments({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        

        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

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

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



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

    ];

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

            
            if (filter.standard_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'quality_standards',
                        'standard_name',
                        filter.standard_name,
                    ),
                };
            }
            
            if (filter.standard_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'quality_standards',
                        'standard_code',
                        filter.standard_code,
                    ),
                };
            }
            
            if (filter.requirements) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'quality_standards',
                        'requirements',
                        filter.requirements,
                    ),
                };
            }
            

            
            

            

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

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


      

      



            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,
                        },
                    };
                }
            }
        }
        

        

        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.quality_standards.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, ) {
        let where = {};
        
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'quality_standards',
                        'standard_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

