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

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

        const carts = await db.carts.create(
            {
                id: data.id || undefined,
        
        cart_status: data.cart_status
        ||
        null
            ,
            
        subtotal_amount: data.subtotal_amount
        ||
        null
            ,
            
        discount_amount: data.discount_amount
        ||
        null
            ,
            
        tax_amount: data.tax_amount
        ||
        null
            ,
            
        total_amount: data.total_amount
        ||
        null
            ,
            
        hold_reason: data.hold_reason
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await carts.setLocation( data.location || null, {
            transaction,
        });
        
        await carts.setRegister( data.register || null, {
            transaction,
        });
        
        await carts.setShift( data.shift || null, {
            transaction,
        });
        
        await carts.setCustomer( data.customer || null, {
            transaction,
        });
        
        await carts.setOpened_by_user( data.opened_by_user || null, {
            transaction,
        });
        
        await carts.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return carts;
    }
    

    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 cartsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                cart_status: item.cart_status
            ||
            null
            ,
            
                subtotal_amount: item.subtotal_amount
            ||
            null
            ,
            
                discount_amount: item.discount_amount
            ||
            null
            ,
            
                tax_amount: item.tax_amount
            ||
            null
            ,
            
                total_amount: item.total_amount
            ||
            null
            ,
            
                hold_reason: item.hold_reason
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return carts;
    }

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

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


        

        const updatePayload = {};
        
        if (data.cart_status !== undefined) updatePayload.cart_status = data.cart_status;
        
        
        if (data.subtotal_amount !== undefined) updatePayload.subtotal_amount = data.subtotal_amount;
        
        
        if (data.discount_amount !== undefined) updatePayload.discount_amount = data.discount_amount;
        
        
        if (data.tax_amount !== undefined) updatePayload.tax_amount = data.tax_amount;
        
        
        if (data.total_amount !== undefined) updatePayload.total_amount = data.total_amount;
        
        
        if (data.hold_reason !== undefined) updatePayload.hold_reason = data.hold_reason;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.location !== undefined) {
            await carts.setLocation(
              
              data.location,
              
              { transaction }
            );
        }
        
        if (data.register !== undefined) {
            await carts.setRegister(
              
              data.register,
              
              { transaction }
            );
        }
        
        if (data.shift !== undefined) {
            await carts.setShift(
              
              data.shift,
              
              { transaction }
            );
        }
        
        if (data.customer !== undefined) {
            await carts.setCustomer(
              
              data.customer,
              
              { transaction }
            );
        }
        
        if (data.opened_by_user !== undefined) {
            await carts.setOpened_by_user(
              
              data.opened_by_user,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await carts.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return carts;
    }

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

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

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


        return carts;
    }

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

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

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

        await carts.destroy({
            transaction
        });

        return carts;
    }

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

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

        if (!carts) {
            return carts;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.cart_items_cart = await carts.getCart_items_cart({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.location = await carts.getLocation({
            transaction
        });
        
        
        output.register = await carts.getRegister({
            transaction
        });
        
        
        output.shift = await carts.getShift({
            transaction
        });
        
        
        output.customer = await carts.getCustomer({
            transaction
        });
        
        
        output.opened_by_user = await carts.getOpened_by_user({
            transaction
        });
        
        
        output.organizations = await carts.getOrganizations({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           globalAccess,  options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        
        const user = (options && options.currentUser) || null;
        const userOrganizations = (user && user.organizations?.id) || null;
        

        
        if (userOrganizations) {
            if (options?.currentUser?.organizationsId) {
                where.organizationsId = options.currentUser.organizationsId;
            }
        }
        

        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)) } },
            {
              location_name: {
                [Op.or]: filter.location.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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

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

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

      {
        model: db.organizations,
        as: 'organizations',
        
      },



    ];

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

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

            
            

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

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

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

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

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

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

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

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


      

      

      

      

      

      
      if (filter.organizations) {
        const listItems = filter.organizations.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          organizationsId: {[Op.or]: listItems}
        };
      }
      



            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,
                        },
                    };
                }
            }
        }
        

        
        if (globalAccess) {
            delete where.organizationsId;
        }
        

        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.carts.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,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'carts',
                        'hold_reason',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

