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

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

        const camera_scan_sessions = await db.camera_scan_sessions.create(
            {
                id: data.id || undefined,
        
        scan_type: data.scan_type
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        started_at: data.started_at
        ||
        null
            ,
            
        ended_at: data.ended_at
        ||
        null
            ,
            
        frames_analyzed: data.frames_analyzed
        ||
        null
            ,
            
        pages_detected: data.pages_detected
        ||
        null
            ,
            
        confidence_score: data.confidence_score
        ||
        null
            ,
            
        page_turning_detected: data.page_turning_detected
        ||
        false
        
            ,
            
        duplicate_page_detected: data.duplicate_page_detected
        ||
        false
        
            ,
            
        fraud_reason: data.fraud_reason
        ||
        null
            ,
            
        coins_awarded: data.coins_awarded
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await camera_scan_sessions.setUser( data.user || null, {
            transaction,
        });
        
        await camera_scan_sessions.setBook( data.book || null, {
            transaction,
        });
        

        

        

        return camera_scan_sessions;
    }
    

    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 camera_scan_sessionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                scan_type: item.scan_type
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                started_at: item.started_at
            ||
            null
            ,
            
                ended_at: item.ended_at
            ||
            null
            ,
            
                frames_analyzed: item.frames_analyzed
            ||
            null
            ,
            
                pages_detected: item.pages_detected
            ||
            null
            ,
            
                confidence_score: item.confidence_score
            ||
            null
            ,
            
                page_turning_detected: item.page_turning_detected
            ||
            false
        
            ,
            
                duplicate_page_detected: item.duplicate_page_detected
            ||
            false
        
            ,
            
                fraud_reason: item.fraud_reason
            ||
            null
            ,
            
                coins_awarded: item.coins_awarded
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return camera_scan_sessions;
    }

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

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


        

        const updatePayload = {};
        
        if (data.scan_type !== undefined) updatePayload.scan_type = data.scan_type;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
        
        
        if (data.ended_at !== undefined) updatePayload.ended_at = data.ended_at;
        
        
        if (data.frames_analyzed !== undefined) updatePayload.frames_analyzed = data.frames_analyzed;
        
        
        if (data.pages_detected !== undefined) updatePayload.pages_detected = data.pages_detected;
        
        
        if (data.confidence_score !== undefined) updatePayload.confidence_score = data.confidence_score;
        
        
        if (data.page_turning_detected !== undefined) updatePayload.page_turning_detected = data.page_turning_detected;
        
        
        if (data.duplicate_page_detected !== undefined) updatePayload.duplicate_page_detected = data.duplicate_page_detected;
        
        
        if (data.fraud_reason !== undefined) updatePayload.fraud_reason = data.fraud_reason;
        
        
        if (data.coins_awarded !== undefined) updatePayload.coins_awarded = data.coins_awarded;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.user !== undefined) {
            await camera_scan_sessions.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        
        if (data.book !== undefined) {
            await camera_scan_sessions.setBook(
              
              data.book,
              
              { transaction }
            );
        }
        

        
        

        

        return camera_scan_sessions;
    }

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

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

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


        return camera_scan_sessions;
    }

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

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

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

        await camera_scan_sessions.destroy({
            transaction
        });

        return camera_scan_sessions;
    }

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

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

        if (!camera_scan_sessions) {
            return camera_scan_sessions;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        output.coin_ledger_entries_scan_session = await camera_scan_sessions.getCoin_ledger_entries_scan_session({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.fraud_flags_scan_session = await camera_scan_sessions.getFraud_flags_scan_session({
            transaction
        });
        
        
        
        
        
        output.user = await camera_scan_sessions.getUser({
            transaction
        });
        
        
        output.book = await camera_scan_sessions.getBook({
            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: 'user',
        
        where: filter.user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.books,
        as: 'book',
        
        where: filter.book ? {
          [Op.or]: [
            { id: { [Op.in]: filter.book.split('|').map(term => Utils.uuid(term)) } },
            {
              title: {
                [Op.or]: filter.book.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.fraud_reason) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'camera_scan_sessions',
                        'fraud_reason',
                        filter.fraud_reason,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
            if (filter.scan_type) {
                where = {
                    ...where,
                scan_type: filter.scan_type,
            };
            }
            
            if (filter.status) {
                where = {
                    ...where,
                status: filter.status,
            };
            }
            
            if (filter.page_turning_detected) {
                where = {
                    ...where,
                page_turning_detected: filter.page_turning_detected,
            };
            }
            
            if (filter.duplicate_page_detected) {
                where = {
                    ...where,
                duplicate_page_detected: filter.duplicate_page_detected,
            };
            }
            


      

      



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

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

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

    
};

