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

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

        const biometric_imports = await db.biometric_imports.create(
            {
                id: data.id || undefined,
        
        importDate: data.importDate
        ||
        null
            ,
            
        deviceCode: data.deviceCode
        ||
        null
            ,
            
        fileName: data.fileName
        ||
        null
            ,
            
        totalRecords: data.totalRecords
        ||
        null
            ,
            
        successCount: data.successCount
        ||
        null
            ,
            
        errorCount: data.errorCount
        ||
        null
            ,
            
        errorDetailsJson: data.errorDetailsJson
        ||
        null
            ,
            
        periodFrom: data.periodFrom
        ||
        null
            ,
            
        periodTo: data.periodTo
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await biometric_imports.setImportedByUser( data.importedByUser || null, {
            transaction,
        });
        

        

        

        return biometric_imports;
    }
    

    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 biometric_importsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                importDate: item.importDate
            ||
            null
            ,
            
                deviceCode: item.deviceCode
            ||
            null
            ,
            
                fileName: item.fileName
            ||
            null
            ,
            
                totalRecords: item.totalRecords
            ||
            null
            ,
            
                successCount: item.successCount
            ||
            null
            ,
            
                errorCount: item.errorCount
            ||
            null
            ,
            
                errorDetailsJson: item.errorDetailsJson
            ||
            null
            ,
            
                periodFrom: item.periodFrom
            ||
            null
            ,
            
                periodTo: item.periodTo
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return biometric_imports;
    }

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

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


        

        const updatePayload = {};
        
        if (data.importDate !== undefined) updatePayload.importDate = data.importDate;
        
        
        if (data.deviceCode !== undefined) updatePayload.deviceCode = data.deviceCode;
        
        
        if (data.fileName !== undefined) updatePayload.fileName = data.fileName;
        
        
        if (data.totalRecords !== undefined) updatePayload.totalRecords = data.totalRecords;
        
        
        if (data.successCount !== undefined) updatePayload.successCount = data.successCount;
        
        
        if (data.errorCount !== undefined) updatePayload.errorCount = data.errorCount;
        
        
        if (data.errorDetailsJson !== undefined) updatePayload.errorDetailsJson = data.errorDetailsJson;
        
        
        if (data.periodFrom !== undefined) updatePayload.periodFrom = data.periodFrom;
        
        
        if (data.periodTo !== undefined) updatePayload.periodTo = data.periodTo;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.importedByUser !== undefined) {
            await biometric_imports.setImportedByUser(
              
              data.importedByUser,
              
              { transaction }
            );
        }
        

        
        

        

        return biometric_imports;
    }

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

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

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


        return biometric_imports;
    }

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

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

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

        await biometric_imports.destroy({
            transaction
        });

        return biometric_imports;
    }

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

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

        if (!biometric_imports) {
            return biometric_imports;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.importedByUser = await biometric_imports.getImportedByUser({
            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.users,
        as: 'importedByUser',
        
        where: filter.importedByUser ? {
          [Op.or]: [
            { id: { [Op.in]: filter.importedByUser.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.importedByUser.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.deviceCode) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'biometric_imports',
                        'deviceCode',
                        filter.deviceCode,
                    ),
                };
            }
            
            if (filter.fileName) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'biometric_imports',
                        'fileName',
                        filter.fileName,
                    ),
                };
            }
            
            if (filter.errorDetailsJson) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'biometric_imports',
                        'errorDetailsJson',
                        filter.errorDetailsJson,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            


      



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

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

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

    
};

