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

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

        const market_stores = await db.market_stores.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        store_status: data.store_status
        ||
        null
            ,
            
        opened_at: data.opened_at
        ||
        null
            ,
            
        closed_at: data.closed_at
        ||
        null
            ,
            
        cash_balance: data.cash_balance
        ||
        null
            ,
            
        pix_balance: data.pix_balance
        ||
        null
            ,
            
        card_balance: data.card_balance
        ||
        null
            ,
            
        store_note: data.store_note
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await market_stores.setLocation( data.location || null, {
            transaction,
        });
        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.market_stores.getTableName(),
                belongsToColumn: 'store_images',
                belongsToId: market_stores.id,
            },
            data.store_images,
            options,
        );
        

        return market_stores;
    }
    

    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 market_storesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                store_status: item.store_status
            ||
            null
            ,
            
                opened_at: item.opened_at
            ||
            null
            ,
            
                closed_at: item.closed_at
            ||
            null
            ,
            
                cash_balance: item.cash_balance
            ||
            null
            ,
            
                pix_balance: item.pix_balance
            ||
            null
            ,
            
                card_balance: item.card_balance
            ||
            null
            ,
            
                store_note: item.store_note
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        
        for (let i = 0; i < market_stores.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.market_stores.getTableName(),
                    belongsToColumn: 'store_images',
                    belongsToId: market_stores[i].id,
                },
                data[i].store_images,
                options,
            );
        }
        

        return market_stores;
    }

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

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.store_status !== undefined) updatePayload.store_status = data.store_status;
        
        
        if (data.opened_at !== undefined) updatePayload.opened_at = data.opened_at;
        
        
        if (data.closed_at !== undefined) updatePayload.closed_at = data.closed_at;
        
        
        if (data.cash_balance !== undefined) updatePayload.cash_balance = data.cash_balance;
        
        
        if (data.pix_balance !== undefined) updatePayload.pix_balance = data.pix_balance;
        
        
        if (data.card_balance !== undefined) updatePayload.card_balance = data.card_balance;
        
        
        if (data.store_note !== undefined) updatePayload.store_note = data.store_note;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.location !== undefined) {
            await market_stores.setLocation(
              
              data.location,
              
              { transaction }
            );
        }
        

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.market_stores.getTableName(),
                belongsToColumn: 'store_images',
                belongsToId: market_stores.id,
            },
            data.store_images,
            options,
        );
        

        return market_stores;
    }

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

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

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


        return market_stores;
    }

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

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

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

        await market_stores.destroy({
            transaction
        });

        return market_stores;
    }

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

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

        if (!market_stores) {
            return market_stores;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.employees_store = await market_stores.getEmployees_store({
            transaction
        });
        
        
        
        output.store_products_store = await market_stores.getStore_products_store({
            transaction
        });
        
        
        
        output.purchase_orders_store = await market_stores.getPurchase_orders_store({
            transaction
        });
        
        
        
        output.deliveries_store = await market_stores.getDeliveries_store({
            transaction
        });
        
        
        output.shelves_store = await market_stores.getShelves_store({
            transaction
        });
        
        
        
        output.cash_registers_store = await market_stores.getCash_registers_store({
            transaction
        });
        
        
        output.sales_transactions_store = await market_stores.getSales_transactions_store({
            transaction
        });
        
        
        
        output.daily_reports_store = await market_stores.getDaily_reports_store({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.location = await market_stores.getLocation({
            transaction
        });
        
        
        output.store_images = await market_stores.getStore_images({
            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.locations,
        as: 'location',
        
        where: filter.location ? {
          [Op.or]: [
            { id: { [Op.in]: filter.location.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.location.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



      {
        model: db.file,
        as: 'store_images',
      },

    ];

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

            
            if (filter.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'market_stores',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.store_note) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'market_stores',
                        'store_note',
                        filter.store_note,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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

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

            
            if (filter.store_status) {
                where = {
                    ...where,
                store_status: filter.store_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.market_stores.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(
                        'market_stores',
                        'name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

