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

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

        const ocr_extractions = await db.ocr_extractions.create(
            {
                id: data.id || undefined,
        
        processed_at: data.processed_at
        ||
        null
            ,
            
        engine: data.engine
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        invoice_number_text: data.invoice_number_text
        ||
        null
            ,
            
        seller_name_text: data.seller_name_text
        ||
        null
            ,
            
        buyer_name_text: data.buyer_name_text
        ||
        null
            ,
            
        tin_number_text: data.tin_number_text
        ||
        null
            ,
            
        invoice_date: data.invoice_date
        ||
        null
            ,
            
        subtotal_amount: data.subtotal_amount
        ||
        null
            ,
            
        vat_amount: data.vat_amount
        ||
        null
            ,
            
        tot_amount: data.tot_amount
        ||
        null
            ,
            
        total_amount: data.total_amount
        ||
        null
            ,
            
        raw_text: data.raw_text
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await ocr_extractions.setReceipt( data.receipt || null, {
            transaction,
        });
        
        await ocr_extractions.setMerchant( data.merchant || null, {
            transaction,
        });
        
        await ocr_extractions.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return ocr_extractions;
    }
    

    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 ocr_extractionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                processed_at: item.processed_at
            ||
            null
            ,
            
                engine: item.engine
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                invoice_number_text: item.invoice_number_text
            ||
            null
            ,
            
                seller_name_text: item.seller_name_text
            ||
            null
            ,
            
                buyer_name_text: item.buyer_name_text
            ||
            null
            ,
            
                tin_number_text: item.tin_number_text
            ||
            null
            ,
            
                invoice_date: item.invoice_date
            ||
            null
            ,
            
                subtotal_amount: item.subtotal_amount
            ||
            null
            ,
            
                vat_amount: item.vat_amount
            ||
            null
            ,
            
                tot_amount: item.tot_amount
            ||
            null
            ,
            
                total_amount: item.total_amount
            ||
            null
            ,
            
                raw_text: item.raw_text
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return ocr_extractions;
    }

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


        

        const updatePayload = {};
        
        if (data.processed_at !== undefined) updatePayload.processed_at = data.processed_at;
        
        
        if (data.engine !== undefined) updatePayload.engine = data.engine;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.invoice_number_text !== undefined) updatePayload.invoice_number_text = data.invoice_number_text;
        
        
        if (data.seller_name_text !== undefined) updatePayload.seller_name_text = data.seller_name_text;
        
        
        if (data.buyer_name_text !== undefined) updatePayload.buyer_name_text = data.buyer_name_text;
        
        
        if (data.tin_number_text !== undefined) updatePayload.tin_number_text = data.tin_number_text;
        
        
        if (data.invoice_date !== undefined) updatePayload.invoice_date = data.invoice_date;
        
        
        if (data.subtotal_amount !== undefined) updatePayload.subtotal_amount = data.subtotal_amount;
        
        
        if (data.vat_amount !== undefined) updatePayload.vat_amount = data.vat_amount;
        
        
        if (data.tot_amount !== undefined) updatePayload.tot_amount = data.tot_amount;
        
        
        if (data.total_amount !== undefined) updatePayload.total_amount = data.total_amount;
        
        
        if (data.raw_text !== undefined) updatePayload.raw_text = data.raw_text;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.receipt !== undefined) {
            await ocr_extractions.setReceipt(
              
              data.receipt,
              
              { transaction }
            );
        }
        
        if (data.merchant !== undefined) {
            await ocr_extractions.setMerchant(
              
              data.merchant,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await ocr_extractions.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return ocr_extractions;
    }

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

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

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


        return ocr_extractions;
    }

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

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

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

        await ocr_extractions.destroy({
            transaction
        });

        return ocr_extractions;
    }

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

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

        if (!ocr_extractions) {
            return ocr_extractions;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.receipt = await ocr_extractions.getReceipt({
            transaction
        });
        
        
        output.merchant = await ocr_extractions.getMerchant({
            transaction
        });
        
        
        output.organizations = await ocr_extractions.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.receipts,
        as: 'receipt',
        
        where: filter.receipt ? {
          [Op.or]: [
            { id: { [Op.in]: filter.receipt.split('|').map(term => Utils.uuid(term)) } },
            {
              source_channel: {
                [Op.or]: filter.receipt.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

      {
        model: db.organizations,
        as: 'organizations',
        
      },



    ];

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

            
            if (filter.invoice_number_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'ocr_extractions',
                        'invoice_number_text',
                        filter.invoice_number_text,
                    ),
                };
            }
            
            if (filter.seller_name_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'ocr_extractions',
                        'seller_name_text',
                        filter.seller_name_text,
                    ),
                };
            }
            
            if (filter.buyer_name_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'ocr_extractions',
                        'buyer_name_text',
                        filter.buyer_name_text,
                    ),
                };
            }
            
            if (filter.tin_number_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'ocr_extractions',
                        'tin_number_text',
                        filter.tin_number_text,
                    ),
                };
            }
            
            if (filter.raw_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'ocr_extractions',
                        'raw_text',
                        filter.raw_text,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


      

      

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

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

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

    
};

