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

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

        const device_master_records = await db.device_master_records.create(
            {
                id: data.id || undefined,
        
        dmr_number: data.dmr_number
        ||
        null
            ,
            
        title: data.title
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        effective_at: data.effective_at
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await device_master_records.setProduct( data.product || null, {
            transaction,
        });
        

        

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

        return device_master_records;
    }
    

    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 device_master_recordsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                dmr_number: item.dmr_number
            ||
            null
            ,
            
                title: item.title
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                effective_at: item.effective_at
            ||
            null
            ,
            
                notes: item.notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return device_master_records;
    }

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

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


        

        const updatePayload = {};
        
        if (data.dmr_number !== undefined) updatePayload.dmr_number = data.dmr_number;
        
        
        if (data.title !== undefined) updatePayload.title = data.title;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.effective_at !== undefined) updatePayload.effective_at = data.effective_at;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.product !== undefined) {
            await device_master_records.setProduct(
              
              data.product,
              
              { transaction }
            );
        }
        

        
        

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

        return device_master_records;
    }

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

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

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


        return device_master_records;
    }

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

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

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

        await device_master_records.destroy({
            transaction
        });

        return device_master_records;
    }

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

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

        if (!device_master_records) {
            return device_master_records;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.product = await device_master_records.getProduct({
            transaction
        });
        
        
        output.dmr_files = await device_master_records.getDmr_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.products,
        as: 'product',
        
        where: filter.product ? {
          [Op.or]: [
            { id: { [Op.in]: filter.product.split('|').map(term => Utils.uuid(term)) } },
            {
              product_name: {
                [Op.or]: filter.product.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



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

    ];

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

            
            if (filter.dmr_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'device_master_records',
                        'dmr_number',
                        filter.dmr_number,
                    ),
                };
            }
            
            if (filter.title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'device_master_records',
                        'title',
                        filter.title,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'device_master_records',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

    
};

