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

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

        const pharmacy_sales_invoices = await db.pharmacy_sales_invoices.create(
            {
                id: data.id || undefined,
        
        invoice_number: data.invoice_number
        ||
        null
            ,
            
        items: data.items
        ||
        null
            ,
            
        total_amount: data.total_amount
        ||
        null
            ,
            
        tax: data.tax
        ||
        null
            ,
            
        final_price: data.final_price
        ||
        null
            ,
            
        date: data.date
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await pharmacy_sales_invoices.setPatient( data.patient || null, {
            transaction,
        });
        
        await pharmacy_sales_invoices.setCashier( data.cashier || null, {
            transaction,
        });
        

        

        

        return pharmacy_sales_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 pharmacy_sales_invoicesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                invoice_number: item.invoice_number
            ||
            null
            ,
            
                items: item.items
            ||
            null
            ,
            
                total_amount: item.total_amount
            ||
            null
            ,
            
                tax: item.tax
            ||
            null
            ,
            
                final_price: item.final_price
            ||
            null
            ,
            
                date: item.date
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return pharmacy_sales_invoices;
    }

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

        const pharmacy_sales_invoices = await db.pharmacy_sales_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.total_amount !== undefined) updatePayload.total_amount = data.total_amount;
        
        
        if (data.tax !== undefined) updatePayload.tax = data.tax;
        
        
        if (data.final_price !== undefined) updatePayload.final_price = data.final_price;
        
        
        if (data.date !== undefined) updatePayload.date = data.date;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return pharmacy_sales_invoices;
    }

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

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

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


        return pharmacy_sales_invoices;
    }

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

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

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

        await pharmacy_sales_invoices.destroy({
            transaction
        });

        return pharmacy_sales_invoices;
    }

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

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

        if (!pharmacy_sales_invoices) {
            return pharmacy_sales_invoices;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.patient = await pharmacy_sales_invoices.getPatient({
            transaction
        });
        
        
        output.cashier = await pharmacy_sales_invoices.getCashier({
            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}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.users,
        as: 'cashier',
        
        where: filter.cashier ? {
          [Op.or]: [
            { id: { [Op.in]: filter.cashier.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.cashier.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(
                        'pharmacy_sales_invoices',
                        'invoice_number',
                        filter.invoice_number,
                    ),
                };
            }
            
            if (filter.items) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'pharmacy_sales_invoices',
                        'items',
                        filter.items,
                    ),
                };
            }
            

            
            

            
            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.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.final_priceRange) {
                const [start, end] = filter.final_priceRange;

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

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

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

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

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

            


      

      



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

        const records = await db.pharmacy_sales_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,
        }));
    }

    
};

