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

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

        const qr_links = await db.qr_links.create(
            {
                id: data.id || undefined,
        
        code_name: data.code_name
        ||
        null
            ,
            
        target_path: data.target_path
        ||
        null
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
        scan_count: data.scan_count
        ||
        null
            ,
            
        last_scanned_at: data.last_scanned_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        

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

        return qr_links;
    }
    

    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 qr_linksData = data.map((item, index) => ({
                id: item.id || undefined,
                
                code_name: item.code_name
            ||
            null
            ,
            
                target_path: item.target_path
            ||
            null
            ,
            
                is_active: item.is_active
            ||
            false
        
            ,
            
                scan_count: item.scan_count
            ||
            null
            ,
            
                last_scanned_at: item.last_scanned_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return qr_links;
    }

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

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


        

        const updatePayload = {};
        
        if (data.code_name !== undefined) updatePayload.code_name = data.code_name;
        
        
        if (data.target_path !== undefined) updatePayload.target_path = data.target_path;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        if (data.scan_count !== undefined) updatePayload.scan_count = data.scan_count;
        
        
        if (data.last_scanned_at !== undefined) updatePayload.last_scanned_at = data.last_scanned_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        

        
        

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

        return qr_links;
    }

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

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

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


        return qr_links;
    }

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

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

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

        await qr_links.destroy({
            transaction
        });

        return qr_links;
    }

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

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

        if (!qr_links) {
            return qr_links;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.qr_image = await qr_links.getQr_image({
            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.file,
        as: 'qr_image',
      },

    ];

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

            
            if (filter.code_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'qr_links',
                        'code_name',
                        filter.code_name,
                    ),
                };
            }
            
            if (filter.target_path) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'qr_links',
                        'target_path',
                        filter.target_path,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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




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

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

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

    
};

