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

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

        const receipts = await db.receipts.create(
            {
                id: data.id || undefined,
        
        receipt_kind: data.receipt_kind
        ||
        null
            ,
            
        source_channel: data.source_channel
        ||
        null
            ,
            
        captured_at: data.captured_at
        ||
        null
            ,
            
        ocr_status: data.ocr_status
        ||
        null
            ,
            
        ocr_confidence: data.ocr_confidence
        ||
        null
            ,
            
        needs_review: data.needs_review
        ||
        false
        
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await receipts.setMerchant( data.merchant || null, {
            transaction,
        });
        
        await receipts.setUploaded_by( data.uploaded_by || null, {
            transaction,
        });
        
        await receipts.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

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

        return receipts;
    }
    

    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 receiptsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                receipt_kind: item.receipt_kind
            ||
            null
            ,
            
                source_channel: item.source_channel
            ||
            null
            ,
            
                captured_at: item.captured_at
            ||
            null
            ,
            
                ocr_status: item.ocr_status
            ||
            null
            ,
            
                ocr_confidence: item.ocr_confidence
            ||
            null
            ,
            
                needs_review: item.needs_review
            ||
            false
        
            ,
            
                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 receipts = await db.receipts.bulkCreate(receiptsData, { transaction });

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

        return receipts;
    }

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


        

        const updatePayload = {};
        
        if (data.receipt_kind !== undefined) updatePayload.receipt_kind = data.receipt_kind;
        
        
        if (data.source_channel !== undefined) updatePayload.source_channel = data.source_channel;
        
        
        if (data.captured_at !== undefined) updatePayload.captured_at = data.captured_at;
        
        
        if (data.ocr_status !== undefined) updatePayload.ocr_status = data.ocr_status;
        
        
        if (data.ocr_confidence !== undefined) updatePayload.ocr_confidence = data.ocr_confidence;
        
        
        if (data.needs_review !== undefined) updatePayload.needs_review = data.needs_review;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.merchant !== undefined) {
            await receipts.setMerchant(
              
              data.merchant,
              
              { transaction }
            );
        }
        
        if (data.uploaded_by !== undefined) {
            await receipts.setUploaded_by(
              
              data.uploaded_by,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await receipts.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

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

        return receipts;
    }

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

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

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


        return receipts;
    }

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

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

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

        await receipts.destroy({
            transaction
        });

        return receipts;
    }

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

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

        if (!receipts) {
            return receipts;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        output.ocr_extractions_receipt = await receipts.getOcr_extractions_receipt({
            transaction
        });
        
        
        output.sales_invoices_receipt = await receipts.getSales_invoices_receipt({
            transaction
        });
        
        
        
        output.purchase_invoices_receipt = await receipts.getPurchase_invoices_receipt({
            transaction
        });
        
        
        
        output.expenses_receipt = await receipts.getExpenses_receipt({
            transaction
        });
        
        
        
        
        
        
        
        
        
        output.merchant = await receipts.getMerchant({
            transaction
        });
        
        
        output.uploaded_by = await receipts.getUploaded_by({
            transaction
        });
        
        
        output.receipt_images = await receipts.getReceipt_images({
            transaction
        });
        
        
        output.receipt_files = await receipts.getReceipt_files({
            transaction
        });
        
        
        output.organizations = await receipts.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.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.users,
        as: 'uploaded_by',
        
        where: filter.uploaded_by ? {
          [Op.or]: [
            { id: { [Op.in]: filter.uploaded_by.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.uploaded_by.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



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

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

    ];

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

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

            
            

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

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

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

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

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

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

            
            if (filter.receipt_kind) {
                where = {
                    ...where,
                receipt_kind: filter.receipt_kind,
            };
            }
            
            if (filter.ocr_status) {
                where = {
                    ...where,
                ocr_status: filter.ocr_status,
            };
            }
            
            if (filter.needs_review) {
                where = {
                    ...where,
                needs_review: filter.needs_review,
            };
            }
            


      

      

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

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

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

    
};

