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

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

        const material_revisions = await db.material_revisions.create(
            {
                id: data.id || undefined,
        
        revision_code: data.revision_code
        ||
        null
            ,
            
        effective_from: data.effective_from
        ||
        null
            ,
            
        effective_to: data.effective_to
        ||
        null
            ,
            
        lifecycle_state: data.lifecycle_state
        ||
        null
            ,
            
        change_summary: data.change_summary
        ||
        null
            ,
            
        approved_at: data.approved_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await material_revisions.setMaterial( data.material || null, {
            transaction,
        });
        
        await material_revisions.setApproved_by_user( data.approved_by_user || null, {
            transaction,
        });
        

        

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

        return material_revisions;
    }
    

    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 material_revisionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                revision_code: item.revision_code
            ||
            null
            ,
            
                effective_from: item.effective_from
            ||
            null
            ,
            
                effective_to: item.effective_to
            ||
            null
            ,
            
                lifecycle_state: item.lifecycle_state
            ||
            null
            ,
            
                change_summary: item.change_summary
            ||
            null
            ,
            
                approved_at: item.approved_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return material_revisions;
    }

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

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


        

        const updatePayload = {};
        
        if (data.revision_code !== undefined) updatePayload.revision_code = data.revision_code;
        
        
        if (data.effective_from !== undefined) updatePayload.effective_from = data.effective_from;
        
        
        if (data.effective_to !== undefined) updatePayload.effective_to = data.effective_to;
        
        
        if (data.lifecycle_state !== undefined) updatePayload.lifecycle_state = data.lifecycle_state;
        
        
        if (data.change_summary !== undefined) updatePayload.change_summary = data.change_summary;
        
        
        if (data.approved_at !== undefined) updatePayload.approved_at = data.approved_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.material !== undefined) {
            await material_revisions.setMaterial(
              
              data.material,
              
              { transaction }
            );
        }
        
        if (data.approved_by_user !== undefined) {
            await material_revisions.setApproved_by_user(
              
              data.approved_by_user,
              
              { transaction }
            );
        }
        

        
        

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

        return material_revisions;
    }

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

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

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


        return material_revisions;
    }

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

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

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

        await material_revisions.destroy({
            transaction
        });

        return material_revisions;
    }

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

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

        if (!material_revisions) {
            return material_revisions;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        output.boms_revision = await material_revisions.getBoms_revision({
            transaction
        });
        
        
        
        output.routings_revision = await material_revisions.getRoutings_revision({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.quality_standards_revision = await material_revisions.getQuality_standards_revision({
            transaction
        });
        
        
        
        
        
        
        
        
        
        output.material = await material_revisions.getMaterial({
            transaction
        });
        
        
        output.approved_by_user = await material_revisions.getApproved_by_user({
            transaction
        });
        
        
        output.spec_files = await material_revisions.getSpec_files({
            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.users,
        as: 'approved_by_user',
        
        where: filter.approved_by_user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.approved_by_user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.approved_by_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



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

    ];

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

            
            if (filter.revision_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'material_revisions',
                        'revision_code',
                        filter.revision_code,
                    ),
                };
            }
            
            if (filter.change_summary) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'material_revisions',
                        'change_summary',
                        filter.change_summary,
                    ),
                };
            }
            

            
            
            if (filter.calendarStart && filter.calendarEnd) {
                where = {
                    ...where,
                    [Op.or]: [
                        {
                            effective_from: {
                                [Op.between]: [filter.calendarStart, filter.calendarEnd],
                            },
                    },
                {
                    effective_to: {
                        [Op.between]: [filter.calendarStart, filter.calendarEnd],
                    },
                },
                ],
            };
            }
            

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    effective_to: {
                    ...where.effective_to,
                            [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.lifecycle_state) {
                where = {
                    ...where,
                lifecycle_state: filter.lifecycle_state,
            };
            }
            


      

      



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

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

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

    
};

