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

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

        const materials = await db.materials.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        material_number: data.material_number
        ||
        null
            ,
            
        material_type: data.material_type
        ||
        null
            ,
            
        uom: data.uom
        ||
        null
            ,
            
        revision: data.revision
        ||
        null
            ,
            
        lot_tracked: data.lot_tracked
        ||
        false
        
            ,
            
        serial_tracked: data.serial_tracked
        ||
        false
        
            ,
            
        active: data.active
        ||
        false
        
            ,
            
        description: data.description
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

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

        return materials;
    }
    

    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 materialsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                material_number: item.material_number
            ||
            null
            ,
            
                material_type: item.material_type
            ||
            null
            ,
            
                uom: item.uom
            ||
            null
            ,
            
                revision: item.revision
            ||
            null
            ,
            
                lot_tracked: item.lot_tracked
            ||
            false
        
            ,
            
                serial_tracked: item.serial_tracked
            ||
            false
        
            ,
            
                active: item.active
            ||
            false
        
            ,
            
                description: item.description
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return materials;
    }

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.material_number !== undefined) updatePayload.material_number = data.material_number;
        
        
        if (data.material_type !== undefined) updatePayload.material_type = data.material_type;
        
        
        if (data.uom !== undefined) updatePayload.uom = data.uom;
        
        
        if (data.revision !== undefined) updatePayload.revision = data.revision;
        
        
        if (data.lot_tracked !== undefined) updatePayload.lot_tracked = data.lot_tracked;
        
        
        if (data.serial_tracked !== undefined) updatePayload.serial_tracked = data.serial_tracked;
        
        
        if (data.active !== undefined) updatePayload.active = data.active;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

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

        return materials;
    }

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

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

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


        return materials;
    }

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

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

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

        await materials.destroy({
            transaction
        });

        return materials;
    }

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

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

        if (!materials) {
            return materials;
        }

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

        
        
        
        
        
        
        
        
        
        output.bom_headers_parent_material = await materials.getBom_headers_parent_material({
            transaction
        });
        
        
        output.bom_lines_component_material = await materials.getBom_lines_component_material({
            transaction
        });
        
        
        output.routings_material = await materials.getRoutings_material({
            transaction
        });
        
        
        
        
        
        
        
        output.lots_material = await materials.getLots_material({
            transaction
        });
        
        
        output.serials_material = await materials.getSerials_material({
            transaction
        });
        
        
        output.inventory_balances_material = await materials.getInventory_balances_material({
            transaction
        });
        
        
        output.inventory_transactions_material = await materials.getInventory_transactions_material({
            transaction
        });
        
        
        
        output.cycle_count_lines_material = await materials.getCycle_count_lines_material({
            transaction
        });
        
        
        output.production_orders_material = await materials.getProduction_orders_material({
            transaction
        });
        
        
        
        output.material_allocations_component_material = await materials.getMaterial_allocations_component_material({
            transaction
        });
        
        
        output.production_lots_material = await materials.getProduction_lots_material({
            transaction
        });
        
        
        output.inspection_plans_material = await materials.getInspection_plans_material({
            transaction
        });
        
        
        
        output.inspections_material = await materials.getInspections_material({
            transaction
        });
        
        
        
        output.nonconformances_material = await materials.getNonconformances_material({
            transaction
        });
        
        
        
        
        
        
        
        
        
        output.shipment_lines_material = await materials.getShipment_lines_material({
            transaction
        });
        
        
        
        output.images = await materials.getImages({
            transaction
        });
        
        
        output.spec_files = await materials.getSpec_files({
            transaction
        });
        
        
        output.organizations = await materials.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',
        
      },



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

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

    ];

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

            
            if (filter.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'materials',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.material_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'materials',
                        'material_number',
                        filter.material_number,
                    ),
                };
            }
            
            if (filter.uom) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'materials',
                        'uom',
                        filter.uom,
                    ),
                };
            }
            
            if (filter.revision) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'materials',
                        'revision',
                        filter.revision,
                    ),
                };
            }
            
            if (filter.description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'materials',
                        'description',
                        filter.description,
                    ),
                };
            }
            

            
            

            

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

            
            if (filter.material_type) {
                where = {
                    ...where,
                material_type: filter.material_type,
            };
            }
            
            if (filter.lot_tracked) {
                where = {
                    ...where,
                lot_tracked: filter.lot_tracked,
            };
            }
            
            if (filter.serial_tracked) {
                where = {
                    ...where,
                serial_tracked: filter.serial_tracked,
            };
            }
            
            if (filter.active) {
                where = {
                    ...where,
                active: filter.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.materials.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(
                        'materials',
                        'name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

