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

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

        const daily_reports = await db.daily_reports.create(
            {
                id: data.id || undefined,
        
        business_date: data.business_date
        ||
        null
            ,
            
        gross_sales: data.gross_sales
        ||
        null
            ,
            
        net_sales: data.net_sales
        ||
        null
            ,
            
        transactions_count: data.transactions_count
        ||
        null
            ,
            
        cash_total: data.cash_total
        ||
        null
            ,
            
        pix_total: data.pix_total
        ||
        null
            ,
            
        card_total: data.card_total
        ||
        null
            ,
            
        wages_paid: data.wages_paid
        ||
        null
            ,
            
        inventory_purchases: data.inventory_purchases
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await daily_reports.setStore( data.store || null, {
            transaction,
        });
        

        

        

        return daily_reports;
    }
    

    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 daily_reportsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                business_date: item.business_date
            ||
            null
            ,
            
                gross_sales: item.gross_sales
            ||
            null
            ,
            
                net_sales: item.net_sales
            ||
            null
            ,
            
                transactions_count: item.transactions_count
            ||
            null
            ,
            
                cash_total: item.cash_total
            ||
            null
            ,
            
                pix_total: item.pix_total
            ||
            null
            ,
            
                card_total: item.card_total
            ||
            null
            ,
            
                wages_paid: item.wages_paid
            ||
            null
            ,
            
                inventory_purchases: item.inventory_purchases
            ||
            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 daily_reports = await db.daily_reports.bulkCreate(daily_reportsData, { transaction });

        // For each item created, replace relation files
        

        return daily_reports;
    }

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

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


        

        const updatePayload = {};
        
        if (data.business_date !== undefined) updatePayload.business_date = data.business_date;
        
        
        if (data.gross_sales !== undefined) updatePayload.gross_sales = data.gross_sales;
        
        
        if (data.net_sales !== undefined) updatePayload.net_sales = data.net_sales;
        
        
        if (data.transactions_count !== undefined) updatePayload.transactions_count = data.transactions_count;
        
        
        if (data.cash_total !== undefined) updatePayload.cash_total = data.cash_total;
        
        
        if (data.pix_total !== undefined) updatePayload.pix_total = data.pix_total;
        
        
        if (data.card_total !== undefined) updatePayload.card_total = data.card_total;
        
        
        if (data.wages_paid !== undefined) updatePayload.wages_paid = data.wages_paid;
        
        
        if (data.inventory_purchases !== undefined) updatePayload.inventory_purchases = data.inventory_purchases;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.store !== undefined) {
            await daily_reports.setStore(
              
              data.store,
              
              { transaction }
            );
        }
        

        
        

        

        return daily_reports;
    }

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

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

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


        return daily_reports;
    }

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

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

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

        await daily_reports.destroy({
            transaction
        });

        return daily_reports;
    }

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

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

        if (!daily_reports) {
            return daily_reports;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.store = await daily_reports.getStore({
            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.market_stores,
        as: 'store',
        
        where: filter.store ? {
          [Op.or]: [
            { id: { [Op.in]: filter.store.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.store.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

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

            
            

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    inventory_purchases: {
                    ...where.inventory_purchases,
                            [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.daily_reports.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(
                        'daily_reports',
                        'notes',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

