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

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

        const sales = await db.sales.create(
            {
                id: data.id || undefined,
        
        number: data.number
        ||
        null
            ,
            
        sale_date: data.sale_date
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        subtotal: data.subtotal
        ||
        null
            ,
            
        discount_total: data.discount_total
        ||
        null
            ,
            
        tax_total: data.tax_total
        ||
        null
            ,
            
        total: data.total
        ||
        null
            ,
            
        payment_status: data.payment_status
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await sales.setClient( data.client || null, {
            transaction,
        });
        
        await sales.setCreated_by_user( data.created_by_user || null, {
            transaction,
        });
        

        

        

        return sales;
    }
    

    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 salesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                number: item.number
            ||
            null
            ,
            
                sale_date: item.sale_date
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                subtotal: item.subtotal
            ||
            null
            ,
            
                discount_total: item.discount_total
            ||
            null
            ,
            
                tax_total: item.tax_total
            ||
            null
            ,
            
                total: item.total
            ||
            null
            ,
            
                payment_status: item.payment_status
            ||
            null
            ,
            
                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 sales = await db.sales.bulkCreate(salesData, { transaction });

        // For each item created, replace relation files
        

        return sales;
    }

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

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


        

        const updatePayload = {};
        
        if (data.number !== undefined) updatePayload.number = data.number;
        
        
        if (data.sale_date !== undefined) updatePayload.sale_date = data.sale_date;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.subtotal !== undefined) updatePayload.subtotal = data.subtotal;
        
        
        if (data.discount_total !== undefined) updatePayload.discount_total = data.discount_total;
        
        
        if (data.tax_total !== undefined) updatePayload.tax_total = data.tax_total;
        
        
        if (data.total !== undefined) updatePayload.total = data.total;
        
        
        if (data.payment_status !== undefined) updatePayload.payment_status = data.payment_status;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.client !== undefined) {
            await sales.setClient(
              
              data.client,
              
              { transaction }
            );
        }
        
        if (data.created_by_user !== undefined) {
            await sales.setCreated_by_user(
              
              data.created_by_user,
              
              { transaction }
            );
        }
        

        
        

        

        return sales;
    }

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

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

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


        return sales;
    }

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

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

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

        await sales.destroy({
            transaction
        });

        return sales;
    }

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

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

        if (!sales) {
            return sales;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        output.sale_items_sale = await sales.getSale_items_sale({
            transaction
        });
        
        
        output.invoices_sale = await sales.getInvoices_sale({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.client = await sales.getClient({
            transaction
        });
        
        
        output.created_by_user = await sales.getCreated_by_user({
            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.clients,
        as: 'client',
        
        where: filter.client ? {
          [Op.or]: [
            { id: { [Op.in]: filter.client.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.client.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

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

            
            

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    sale_date: {
                    ...where.sale_date,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            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.discount_totalRange) {
                const [start, end] = filter.discount_totalRange;

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    tax_total: {
                    ...where.tax_total,
                            [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.active !== undefined) {
                where = {
                    ...where,
                    active: filter.active === true || filter.active === 'true'
                };
            }

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


      

      



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

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

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

    
};

