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

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

        const reseller_stores = await db.reseller_stores.create(
            {
                id: data.id || undefined,
        
        store_name: data.store_name
        ||
        null
            ,
            
        slug: data.slug
        ||
        null
            ,
            
        store_status: data.store_status
        ||
        null
            ,
            
        tagline: data.tagline
        ||
        null
            ,
            
        about: data.about
        ||
        null
            ,
            
        whatsapp_number: data.whatsapp_number
        ||
        null
            ,
            
        instagram_handle: data.instagram_handle
        ||
        null
            ,
            
        tiktok_handle: data.tiktok_handle
        ||
        null
            ,
            
        custom_domain: data.custom_domain
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await reseller_stores.setTenant( data.tenant || null, {
            transaction,
        });
        
        await reseller_stores.setOwner_user( data.owner_user || null, {
            transaction,
        });
        
        await reseller_stores.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

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

        return reseller_stores;
    }
    

    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 reseller_storesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                store_name: item.store_name
            ||
            null
            ,
            
                slug: item.slug
            ||
            null
            ,
            
                store_status: item.store_status
            ||
            null
            ,
            
                tagline: item.tagline
            ||
            null
            ,
            
                about: item.about
            ||
            null
            ,
            
                whatsapp_number: item.whatsapp_number
            ||
            null
            ,
            
                instagram_handle: item.instagram_handle
            ||
            null
            ,
            
                tiktok_handle: item.tiktok_handle
            ||
            null
            ,
            
                custom_domain: item.custom_domain
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return reseller_stores;
    }

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


        

        const updatePayload = {};
        
        if (data.store_name !== undefined) updatePayload.store_name = data.store_name;
        
        
        if (data.slug !== undefined) updatePayload.slug = data.slug;
        
        
        if (data.store_status !== undefined) updatePayload.store_status = data.store_status;
        
        
        if (data.tagline !== undefined) updatePayload.tagline = data.tagline;
        
        
        if (data.about !== undefined) updatePayload.about = data.about;
        
        
        if (data.whatsapp_number !== undefined) updatePayload.whatsapp_number = data.whatsapp_number;
        
        
        if (data.instagram_handle !== undefined) updatePayload.instagram_handle = data.instagram_handle;
        
        
        if (data.tiktok_handle !== undefined) updatePayload.tiktok_handle = data.tiktok_handle;
        
        
        if (data.custom_domain !== undefined) updatePayload.custom_domain = data.custom_domain;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.tenant !== undefined) {
            await reseller_stores.setTenant(
              
              data.tenant,
              
              { transaction }
            );
        }
        
        if (data.owner_user !== undefined) {
            await reseller_stores.setOwner_user(
              
              data.owner_user,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await reseller_stores.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

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

        return reseller_stores;
    }

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

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

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


        return reseller_stores;
    }

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

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

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

        await reseller_stores.destroy({
            transaction
        });

        return reseller_stores;
    }

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

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

        if (!reseller_stores) {
            return reseller_stores;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.store_pages_reseller_store = await reseller_stores.getStore_pages_reseller_store({
            transaction
        });
        
        
        
        
        
        
        output.tenant = await reseller_stores.getTenant({
            transaction
        });
        
        
        output.owner_user = await reseller_stores.getOwner_user({
            transaction
        });
        
        
        output.banner_images = await reseller_stores.getBanner_images({
            transaction
        });
        
        
        output.organizations = await reseller_stores.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.tenants,
        as: 'tenant',
        
        where: filter.tenant ? {
          [Op.or]: [
            { id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
            {
              tenant_name: {
                [Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

      {
        model: db.organizations,
        as: 'organizations',
        
      },



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

    ];

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

            
            if (filter.store_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'reseller_stores',
                        'store_name',
                        filter.store_name,
                    ),
                };
            }
            
            if (filter.slug) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'reseller_stores',
                        'slug',
                        filter.slug,
                    ),
                };
            }
            
            if (filter.tagline) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'reseller_stores',
                        'tagline',
                        filter.tagline,
                    ),
                };
            }
            
            if (filter.about) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'reseller_stores',
                        'about',
                        filter.about,
                    ),
                };
            }
            
            if (filter.whatsapp_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'reseller_stores',
                        'whatsapp_number',
                        filter.whatsapp_number,
                    ),
                };
            }
            
            if (filter.instagram_handle) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'reseller_stores',
                        'instagram_handle',
                        filter.instagram_handle,
                    ),
                };
            }
            
            if (filter.tiktok_handle) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'reseller_stores',
                        'tiktok_handle',
                        filter.tiktok_handle,
                    ),
                };
            }
            
            if (filter.custom_domain) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'reseller_stores',
                        'custom_domain',
                        filter.custom_domain,
                    ),
                };
            }
            

            
            

            

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

            
            if (filter.store_status) {
                where = {
                    ...where,
                store_status: filter.store_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.reseller_stores.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(
                        'reseller_stores',
                        'store_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

