
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,
        
        session_key: data.session_key
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        subtotal_iqd: data.subtotal_iqd
        ||
        null
            ,
            
        discount_total_iqd: data.discount_total_iqd
        ||
        null
            ,
            
        shipping_total_iqd: data.shipping_total_iqd
        ||
        null
            ,
            
        grand_total_iqd: data.grand_total_iqd
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await carts.setUser( data.user || null, {
            transaction,
        });
        
        await carts.setApplied_coupon( data.applied_coupon || null, {
            transaction,
        });
        

        
        await carts.setItems(data.items || [], {
            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,
                
                session_key: item.session_key
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                subtotal_iqd: item.subtotal_iqd
            ||
            null
            ,
            
                discount_total_iqd: item.discount_total_iqd
            ||
            null
            ,
            
                shipping_total_iqd: item.shipping_total_iqd
            ||
            null
            ,
            
                grand_total_iqd: item.grand_total_iqd
            ||
            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.session_key !== undefined) updatePayload.session_key = data.session_key;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.subtotal_iqd !== undefined) updatePayload.subtotal_iqd = data.subtotal_iqd;
        
        
        if (data.discount_total_iqd !== undefined) updatePayload.discount_total_iqd = data.discount_total_iqd;
        
        
        if (data.shipping_total_iqd !== undefined) updatePayload.shipping_total_iqd = data.shipping_total_iqd;
        
        
        if (data.grand_total_iqd !== undefined) updatePayload.grand_total_iqd = data.grand_total_iqd;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.user !== undefined) {
            await carts.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        
        if (data.applied_coupon !== undefined) {
            await carts.setApplied_coupon(
              
              data.applied_coupon,
              
              { transaction }
            );
        }
        

        
        
        if (data.items !== undefined) {
            await carts.setItems(data.items, { 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.user = await carts.getUser({
            transaction
        });
        
        
        output.applied_coupon = await carts.getApplied_coupon({
            transaction
        });
        
        
        output.items = await carts.getItems({
            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.users,
        as: 'user',
        
        where: filter.user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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


      {
        model: db.cart_items,
        as: 'items',
        required: false,
      },


    ];

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

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

            
            

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

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

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    grand_total_iqd: {
                    ...where.grand_total_iqd,
                            [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.items) {
        const searchTerms = filter.items.split('|');

        include = [
          {
            model: db.cart_items,
            as: 'items_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  line_total_iqd: {
                    [Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
                  }
                }
              ]
            } : undefined
          },
          ...include,
        ]
      }


            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',
                        'session_key',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

