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

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

        const merchant_profiles = await db.merchant_profiles.create(
            {
                id: data.id || undefined,
        
        business_name: data.business_name
        ||
        null
            ,
            
        merchant_type: data.merchant_type
        ||
        null
            ,
            
        business_phone: data.business_phone
        ||
        null
            ,
            
        support_email: data.support_email
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
        is_verified: data.is_verified
        ||
        false
        
            ,
            
        verified_at: data.verified_at
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await merchant_profiles.setUser( data.user || null, {
            transaction,
        });
        
        await merchant_profiles.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.merchant_profiles.getTableName(),
                belongsToColumn: 'logo_images',
                belongsToId: merchant_profiles.id,
            },
            data.logo_images,
            options,
        );
        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.merchant_profiles.getTableName(),
                belongsToColumn: 'banner_images',
                belongsToId: merchant_profiles.id,
            },
            data.banner_images,
            options,
        );
        

        return merchant_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 merchant_profilesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                business_name: item.business_name
            ||
            null
            ,
            
                merchant_type: item.merchant_type
            ||
            null
            ,
            
                business_phone: item.business_phone
            ||
            null
            ,
            
                support_email: item.support_email
            ||
            null
            ,
            
                description: item.description
            ||
            null
            ,
            
                is_verified: item.is_verified
            ||
            false
        
            ,
            
                verified_at: item.verified_at
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        
        for (let i = 0; i < merchant_profiles.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.merchant_profiles.getTableName(),
                    belongsToColumn: 'logo_images',
                    belongsToId: merchant_profiles[i].id,
                },
                data[i].logo_images,
                options,
            );
        }
        
        for (let i = 0; i < merchant_profiles.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.merchant_profiles.getTableName(),
                    belongsToColumn: 'banner_images',
                    belongsToId: merchant_profiles[i].id,
                },
                data[i].banner_images,
                options,
            );
        }
        

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


        

        const updatePayload = {};
        
        if (data.business_name !== undefined) updatePayload.business_name = data.business_name;
        
        
        if (data.merchant_type !== undefined) updatePayload.merchant_type = data.merchant_type;
        
        
        if (data.business_phone !== undefined) updatePayload.business_phone = data.business_phone;
        
        
        if (data.support_email !== undefined) updatePayload.support_email = data.support_email;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        if (data.is_verified !== undefined) updatePayload.is_verified = data.is_verified;
        
        
        if (data.verified_at !== undefined) updatePayload.verified_at = data.verified_at;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.user !== undefined) {
            await merchant_profiles.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await merchant_profiles.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.merchant_profiles.getTableName(),
                belongsToColumn: 'logo_images',
                belongsToId: merchant_profiles.id,
            },
            data.logo_images,
            options,
        );
        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.merchant_profiles.getTableName(),
                belongsToColumn: 'banner_images',
                belongsToId: merchant_profiles.id,
            },
            data.banner_images,
            options,
        );
        

        return merchant_profiles;
    }

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

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

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


        return merchant_profiles;
    }

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

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

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

        await merchant_profiles.destroy({
            transaction
        });

        return merchant_profiles;
    }

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

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

        if (!merchant_profiles) {
            return merchant_profiles;
        }

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

        
        
        
        
        
        
        
        output.stores_merchant_profile = await merchant_profiles.getStores_merchant_profile({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await merchant_profiles.getUser({
            transaction
        });
        
        
        output.logo_images = await merchant_profiles.getLogo_images({
            transaction
        });
        
        
        output.banner_images = await merchant_profiles.getBanner_images({
            transaction
        });
        
        
        output.organizations = await merchant_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.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.organizations,
        as: 'organizations',
        
      },



      {
        model: db.file,
        as: 'logo_images',
      },

      {
        model: db.file,
        as: 'banner_images',
      },

    ];

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

            
            if (filter.business_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'merchant_profiles',
                        'business_name',
                        filter.business_name,
                    ),
                };
            }
            
            if (filter.business_phone) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'merchant_profiles',
                        'business_phone',
                        filter.business_phone,
                    ),
                };
            }
            
            if (filter.support_email) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'merchant_profiles',
                        'support_email',
                        filter.support_email,
                    ),
                };
            }
            
            if (filter.description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'merchant_profiles',
                        'description',
                        filter.description,
                    ),
                };
            }
            

            
            

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

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

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

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

            
            if (filter.merchant_type) {
                where = {
                    ...where,
                merchant_type: filter.merchant_type,
            };
            }
            
            if (filter.is_verified) {
                where = {
                    ...where,
                is_verified: filter.is_verified,
            };
            }
            
            if (filter.status) {
                where = {
                    ...where,
                status: filter.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.merchant_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(
                        'merchant_profiles',
                        'business_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

