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

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

        const stores = await db.stores.create(
            {
                id: data.id || undefined,
        
        store_name: data.store_name
        ||
        null
            ,
            
        shopify_domain: data.shopify_domain
        ||
        null
            ,
            
        shopify_storefront_url: data.shopify_storefront_url
        ||
        null
            ,
            
        currency_code: data.currency_code
        ||
        null
            ,
            
        primary_locale: data.primary_locale
        ||
        null
            ,
            
        is_connected: data.is_connected
        ||
        false
        
            ,
            
        connected_at: data.connected_at
        ||
        null
            ,
            
        shopify_api_version: data.shopify_api_version
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await stores.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return 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 storesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                store_name: item.store_name
            ||
            null
            ,
            
                shopify_domain: item.shopify_domain
            ||
            null
            ,
            
                shopify_storefront_url: item.shopify_storefront_url
            ||
            null
            ,
            
                currency_code: item.currency_code
            ||
            null
            ,
            
                primary_locale: item.primary_locale
            ||
            null
            ,
            
                is_connected: item.is_connected
            ||
            false
        
            ,
            
                connected_at: item.connected_at
            ||
            null
            ,
            
                shopify_api_version: item.shopify_api_version
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

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


        

        const updatePayload = {};
        
        if (data.store_name !== undefined) updatePayload.store_name = data.store_name;
        
        
        if (data.shopify_domain !== undefined) updatePayload.shopify_domain = data.shopify_domain;
        
        
        if (data.shopify_storefront_url !== undefined) updatePayload.shopify_storefront_url = data.shopify_storefront_url;
        
        
        if (data.currency_code !== undefined) updatePayload.currency_code = data.currency_code;
        
        
        if (data.primary_locale !== undefined) updatePayload.primary_locale = data.primary_locale;
        
        
        if (data.is_connected !== undefined) updatePayload.is_connected = data.is_connected;
        
        
        if (data.connected_at !== undefined) updatePayload.connected_at = data.connected_at;
        
        
        if (data.shopify_api_version !== undefined) updatePayload.shopify_api_version = data.shopify_api_version;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return stores;
    }

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

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

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


        return stores;
    }

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

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

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

        await stores.destroy({
            transaction
        });

        return stores;
    }

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

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

        if (!stores) {
            return stores;
        }

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

        
        
        
        
        
        
        output.pages_store = await stores.getPages_store({
            transaction
        });
        
        
        output.collections_store = await stores.getCollections_store({
            transaction
        });
        
        
        output.products_store = await stores.getProducts_store({
            transaction
        });
        
        
        
        output.customers_store = await stores.getCustomers_store({
            transaction
        });
        
        
        
        output.orders_store = await stores.getOrders_store({
            transaction
        });
        
        
        
        
        
        output.discount_codes_store = await stores.getDiscount_codes_store({
            transaction
        });
        
        
        
        
        output.faq_articles_store = await stores.getFaq_articles_store({
            transaction
        });
        
        
        output.chatbot_configs_store = await stores.getChatbot_configs_store({
            transaction
        });
        
        
        output.chat_sessions_store = await stores.getChat_sessions_store({
            transaction
        });
        
        
        
        output.support_tickets_store = await stores.getSupport_tickets_store({
            transaction
        });
        
        
        output.shopify_sync_jobs_store = await stores.getShopify_sync_jobs_store({
            transaction
        });
        
        
        
        output.organizations = await 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.organizations,
        as: 'organizations',
        
      },



    ];

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

            
            if (filter.store_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'stores',
                        'store_name',
                        filter.store_name,
                    ),
                };
            }
            
            if (filter.shopify_domain) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'stores',
                        'shopify_domain',
                        filter.shopify_domain,
                    ),
                };
            }
            
            if (filter.shopify_storefront_url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'stores',
                        'shopify_storefront_url',
                        filter.shopify_storefront_url,
                    ),
                };
            }
            
            if (filter.currency_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'stores',
                        'currency_code',
                        filter.currency_code,
                    ),
                };
            }
            
            if (filter.primary_locale) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'stores',
                        'primary_locale',
                        filter.primary_locale,
                    ),
                };
            }
            
            if (filter.shopify_api_version) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'stores',
                        'shopify_api_version',
                        filter.shopify_api_version,
                    ),
                };
            }
            

            
            

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

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

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

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

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


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

        const records = await db.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,
        }));
    }

    
};

