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

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

        const shipping_methods = await db.shipping_methods.create(
            {
                id: data.id || undefined,
        
        method_name: data.method_name
        ||
        null
            ,
            
        base_cost: data.base_cost
        ||
        null
            ,
            
        free_shipping_threshold: data.free_shipping_threshold
        ||
        null
            ,
            
        service_level: data.service_level
        ||
        null
            ,
            
        active: data.active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await shipping_methods.setCarrier( data.carrier || null, {
            transaction,
        });
        

        

        

        return shipping_methods;
    }
    

    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 shipping_methodsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                method_name: item.method_name
            ||
            null
            ,
            
                base_cost: item.base_cost
            ||
            null
            ,
            
                free_shipping_threshold: item.free_shipping_threshold
            ||
            null
            ,
            
                service_level: item.service_level
            ||
            null
            ,
            
                active: item.active
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return shipping_methods;
    }

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

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


        

        const updatePayload = {};
        
        if (data.method_name !== undefined) updatePayload.method_name = data.method_name;
        
        
        if (data.base_cost !== undefined) updatePayload.base_cost = data.base_cost;
        
        
        if (data.free_shipping_threshold !== undefined) updatePayload.free_shipping_threshold = data.free_shipping_threshold;
        
        
        if (data.service_level !== undefined) updatePayload.service_level = data.service_level;
        
        
        if (data.active !== undefined) updatePayload.active = data.active;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.carrier !== undefined) {
            await shipping_methods.setCarrier(
              
              data.carrier,
              
              { transaction }
            );
        }
        

        
        

        

        return shipping_methods;
    }

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

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

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


        return shipping_methods;
    }

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

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

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

        await shipping_methods.destroy({
            transaction
        });

        return shipping_methods;
    }

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

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

        if (!shipping_methods) {
            return shipping_methods;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.orders_shipping_method = await shipping_methods.getOrders_shipping_method({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.carrier = await shipping_methods.getCarrier({
            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.shipping_carriers,
        as: 'carrier',
        
        where: filter.carrier ? {
          [Op.or]: [
            { id: { [Op.in]: filter.carrier.split('|').map(term => Utils.uuid(term)) } },
            {
              carrier_name: {
                [Op.or]: filter.carrier.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

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

            
            

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

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

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

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

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

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

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


      



            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.shipping_methods.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(
                        'shipping_methods',
                        'method_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

