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

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

        const patient_invoices = await db.patient_invoices.create(
            {
                id: data.id || undefined,
        
        invoice_number: data.invoice_number
        ||
        null
            ,
            
        items: data.items
        ||
        null
            ,
            
        subtotal: data.subtotal
        ||
        null
            ,
            
        tax: data.tax
        ||
        null
            ,
            
        total: data.total
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        hide_real_price: data.hide_real_price
        ||
        false
        
            ,
            
        print_price: data.print_price
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await patient_invoices.setPatient( data.patient || null, {
            transaction,
        });
        

        

        

        return patient_invoices;
    }
    

    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 patient_invoicesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                invoice_number: item.invoice_number
            ||
            null
            ,
            
                items: item.items
            ||
            null
            ,
            
                subtotal: item.subtotal
            ||
            null
            ,
            
                tax: item.tax
            ||
            null
            ,
            
                total: item.total
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                hide_real_price: item.hide_real_price
            ||
            false
        
            ,
            
                print_price: item.print_price
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return patient_invoices;
    }

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

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


        

        const updatePayload = {};
        
        if (data.invoice_number !== undefined) updatePayload.invoice_number = data.invoice_number;
        
        
        if (data.items !== undefined) updatePayload.items = data.items;
        
        
        if (data.subtotal !== undefined) updatePayload.subtotal = data.subtotal;
        
        
        if (data.tax !== undefined) updatePayload.tax = data.tax;
        
        
        if (data.total !== undefined) updatePayload.total = data.total;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.hide_real_price !== undefined) updatePayload.hide_real_price = data.hide_real_price;
        
        
        if (data.print_price !== undefined) updatePayload.print_price = data.print_price;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.patient !== undefined) {
            await patient_invoices.setPatient(
              
              data.patient,
              
              { transaction }
            );
        }
        

        
        

        

        return patient_invoices;
    }

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

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

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


        return patient_invoices;
    }

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

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

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

        await patient_invoices.destroy({
            transaction
        });

        return patient_invoices;
    }

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

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

        if (!patient_invoices) {
            return patient_invoices;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.patient = await patient_invoices.getPatient({
            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.patients,
        as: 'patient',
        
        where: filter.patient ? {
          [Op.or]: [
            { id: { [Op.in]: filter.patient.split('|').map(term => Utils.uuid(term)) } },
            {
              full_name: {
                [Op.or]: filter.patient.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.invoice_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'patient_invoices',
                        'invoice_number',
                        filter.invoice_number,
                    ),
                };
            }
            
            if (filter.items) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'patient_invoices',
                        'items',
                        filter.items,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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


      



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

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

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

    
};

