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

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

        const efris_submissions = await db.efris_submissions.create(
            {
                id: data.id || undefined,
        
        document_type: data.document_type
        ||
        null
            ,
            
        submission_status: data.submission_status
        ||
        null
            ,
            
        submitted_at: data.submitted_at
        ||
        null
            ,
            
        last_attempt_at: data.last_attempt_at
        ||
        null
            ,
            
        attempt_count: data.attempt_count
        ||
        null
            ,
            
        request_payload_json: data.request_payload_json
        ||
        null
            ,
            
        response_payload_json: data.response_payload_json
        ||
        null
            ,
            
        efris_invoice_no: data.efris_invoice_no
        ||
        null
            ,
            
        efris_receipt_no: data.efris_receipt_no
        ||
        null
            ,
            
        verification_code: data.verification_code
        ||
        null
            ,
            
        qr_code_data: data.qr_code_data
        ||
        null
            ,
            
        error_code: data.error_code
        ||
        null
            ,
            
        error_message: data.error_message
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await efris_submissions.setOrganization(currentUser.organization.id || null, {
            transaction,
        });
        
        await efris_submissions.setInvoice( data.invoice || null, {
            transaction,
        });
        
        await efris_submissions.setReceipt( data.receipt || null, {
            transaction,
        });
        

        

        

        return efris_submissions;
    }
    

    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 efris_submissionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                document_type: item.document_type
            ||
            null
            ,
            
                submission_status: item.submission_status
            ||
            null
            ,
            
                submitted_at: item.submitted_at
            ||
            null
            ,
            
                last_attempt_at: item.last_attempt_at
            ||
            null
            ,
            
                attempt_count: item.attempt_count
            ||
            null
            ,
            
                request_payload_json: item.request_payload_json
            ||
            null
            ,
            
                response_payload_json: item.response_payload_json
            ||
            null
            ,
            
                efris_invoice_no: item.efris_invoice_no
            ||
            null
            ,
            
                efris_receipt_no: item.efris_receipt_no
            ||
            null
            ,
            
                verification_code: item.verification_code
            ||
            null
            ,
            
                qr_code_data: item.qr_code_data
            ||
            null
            ,
            
                error_code: item.error_code
            ||
            null
            ,
            
                error_message: item.error_message
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return efris_submissions;
    }

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


        

        const updatePayload = {};
        
        if (data.document_type !== undefined) updatePayload.document_type = data.document_type;
        
        
        if (data.submission_status !== undefined) updatePayload.submission_status = data.submission_status;
        
        
        if (data.submitted_at !== undefined) updatePayload.submitted_at = data.submitted_at;
        
        
        if (data.last_attempt_at !== undefined) updatePayload.last_attempt_at = data.last_attempt_at;
        
        
        if (data.attempt_count !== undefined) updatePayload.attempt_count = data.attempt_count;
        
        
        if (data.request_payload_json !== undefined) updatePayload.request_payload_json = data.request_payload_json;
        
        
        if (data.response_payload_json !== undefined) updatePayload.response_payload_json = data.response_payload_json;
        
        
        if (data.efris_invoice_no !== undefined) updatePayload.efris_invoice_no = data.efris_invoice_no;
        
        
        if (data.efris_receipt_no !== undefined) updatePayload.efris_receipt_no = data.efris_receipt_no;
        
        
        if (data.verification_code !== undefined) updatePayload.verification_code = data.verification_code;
        
        
        if (data.qr_code_data !== undefined) updatePayload.qr_code_data = data.qr_code_data;
        
        
        if (data.error_code !== undefined) updatePayload.error_code = data.error_code;
        
        
        if (data.error_message !== undefined) updatePayload.error_message = data.error_message;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.organization !== undefined) {
            await efris_submissions.setOrganization(
              
              (globalAccess ? data.organization : currentUser.organization.id),
              
              { transaction }
            );
        }
        
        if (data.invoice !== undefined) {
            await efris_submissions.setInvoice(
              
              data.invoice,
              
              { transaction }
            );
        }
        
        if (data.receipt !== undefined) {
            await efris_submissions.setReceipt(
              
              data.receipt,
              
              { transaction }
            );
        }
        

        
        

        

        return efris_submissions;
    }

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

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

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


        return efris_submissions;
    }

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

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

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

        await efris_submissions.destroy({
            transaction
        });

        return efris_submissions;
    }

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

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

        if (!efris_submissions) {
            return efris_submissions;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.organization = await efris_submissions.getOrganization({
            transaction
        });
        
        
        output.invoice = await efris_submissions.getInvoice({
            transaction
        });
        
        
        output.receipt = await efris_submissions.getReceipt({
            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.organizations,
        as: 'organization',
        
      },

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

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



    ];

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

            
            if (filter.request_payload_json) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'efris_submissions',
                        'request_payload_json',
                        filter.request_payload_json,
                    ),
                };
            }
            
            if (filter.response_payload_json) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'efris_submissions',
                        'response_payload_json',
                        filter.response_payload_json,
                    ),
                };
            }
            
            if (filter.efris_invoice_no) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'efris_submissions',
                        'efris_invoice_no',
                        filter.efris_invoice_no,
                    ),
                };
            }
            
            if (filter.efris_receipt_no) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'efris_submissions',
                        'efris_receipt_no',
                        filter.efris_receipt_no,
                    ),
                };
            }
            
            if (filter.verification_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'efris_submissions',
                        'verification_code',
                        filter.verification_code,
                    ),
                };
            }
            
            if (filter.qr_code_data) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'efris_submissions',
                        'qr_code_data',
                        filter.qr_code_data,
                    ),
                };
            }
            
            if (filter.error_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'efris_submissions',
                        'error_code',
                        filter.error_code,
                    ),
                };
            }
            
            if (filter.error_message) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'efris_submissions',
                        'error_message',
                        filter.error_message,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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


      
      if (filter.organization) {
        const listItems = filter.organization.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          organizationId: {[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.efris_submissions.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(
                        'efris_submissions',
                        'document_type',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

