
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
            ,
            
        po_number: data.po_number
        ||
        null
            ,
            
        requested_delivery_date: data.requested_delivery_date
        ||
        null
            ,
            
        buyer_notes: data.buyer_notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await carts.setAccount( data.account || null, {
            transaction,
        });
        
        await carts.setLocation( data.location || null, {
            transaction,
        });
        
        await carts.setBuyer( data.buyer || 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
            ,
            
                po_number: item.po_number
            ||
            null
            ,
            
                requested_delivery_date: item.requested_delivery_date
            ||
            null
            ,
            
                buyer_notes: item.buyer_notes
            ||
            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 carts = await db.carts.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.cart_status !== undefined) updatePayload.cart_status = data.cart_status;
        
        
        if (data.po_number !== undefined) updatePayload.po_number = data.po_number;
        
        
        if (data.requested_delivery_date !== undefined) updatePayload.requested_delivery_date = data.requested_delivery_date;
        
        
        if (data.buyer_notes !== undefined) updatePayload.buyer_notes = data.buyer_notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.account !== undefined) {
            await carts.setAccount(
              
              data.account,
              
              { transaction }
            );
        }
        
        if (data.location !== undefined) {
            await carts.setLocation(
              
              data.location,
              
              { transaction }
            );
        }
        
        if (data.buyer !== undefined) {
            await carts.setBuyer(
              
              data.buyer,
              
              { 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.account = await carts.getAccount({
            transaction
        });
        
        
        output.location = await carts.getLocation({
            transaction
        });
        
        
        output.buyer = await carts.getBuyer({
            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.accounts,
        as: 'account',
        
        where: filter.account ? {
          [Op.or]: [
            { id: { [Op.in]: filter.account.split('|').map(term => Utils.uuid(term)) } },
            {
              account_name: {
                [Op.or]: filter.account.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        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.users,
        as: 'buyer',
        
        where: filter.buyer ? {
          [Op.or]: [
            { id: { [Op.in]: filter.buyer.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.buyer.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

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

            
            

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

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

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

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

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

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

    
};

