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

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

        const shipping_profiles = await db.shipping_profiles.create(
            {
                id: data.id || undefined,
        
        profile_name: data.profile_name
        ||
        null
            ,
            
        origin_country: data.origin_country
        ||
        null
            ,
            
        origin_region: data.origin_region
        ||
        null
            ,
            
        origin_postal_code: data.origin_postal_code
        ||
        null
            ,
            
        rules_json: data.rules_json
        ||
        null
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await shipping_profiles.setMerch_store( data.merch_store || null, {
            transaction,
        });
        
        await shipping_profiles.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return shipping_profiles;
    }
    

    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_profilesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                profile_name: item.profile_name
            ||
            null
            ,
            
                origin_country: item.origin_country
            ||
            null
            ,
            
                origin_region: item.origin_region
            ||
            null
            ,
            
                origin_postal_code: item.origin_postal_code
            ||
            null
            ,
            
                rules_json: item.rules_json
            ||
            null
            ,
            
                is_active: item.is_active
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return shipping_profiles;
    }

    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 shipping_profiles = await db.shipping_profiles.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.profile_name !== undefined) updatePayload.profile_name = data.profile_name;
        
        
        if (data.origin_country !== undefined) updatePayload.origin_country = data.origin_country;
        
        
        if (data.origin_region !== undefined) updatePayload.origin_region = data.origin_region;
        
        
        if (data.origin_postal_code !== undefined) updatePayload.origin_postal_code = data.origin_postal_code;
        
        
        if (data.rules_json !== undefined) updatePayload.rules_json = data.rules_json;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.merch_store !== undefined) {
            await shipping_profiles.setMerch_store(
              
              data.merch_store,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await shipping_profiles.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return shipping_profiles;
    }

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

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

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


        return shipping_profiles;
    }

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

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

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

        await shipping_profiles.destroy({
            transaction
        });

        return shipping_profiles;
    }

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

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

        if (!shipping_profiles) {
            return shipping_profiles;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.merch_store = await shipping_profiles.getMerch_store({
            transaction
        });
        
        
        output.organizations = await shipping_profiles.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.merch_stores,
        as: 'merch_store',
        
        where: filter.merch_store ? {
          [Op.or]: [
            { id: { [Op.in]: filter.merch_store.split('|').map(term => Utils.uuid(term)) } },
            {
              store_name: {
                [Op.or]: filter.merch_store.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.profile_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'shipping_profiles',
                        'profile_name',
                        filter.profile_name,
                    ),
                };
            }
            
            if (filter.origin_country) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'shipping_profiles',
                        'origin_country',
                        filter.origin_country,
                    ),
                };
            }
            
            if (filter.origin_region) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'shipping_profiles',
                        'origin_region',
                        filter.origin_region,
                    ),
                };
            }
            
            if (filter.origin_postal_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'shipping_profiles',
                        'origin_postal_code',
                        filter.origin_postal_code,
                    ),
                };
            }
            
            if (filter.rules_json) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'shipping_profiles',
                        'rules_json',
                        filter.rules_json,
                    ),
                };
            }
            

            
            

            

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

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


      

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

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

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

    
};

