
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
            ,
            
        store_slug: data.store_slug
        ||
        null
            ,
            
        store_type: data.store_type
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
        support_phone: data.support_phone
        ||
        null
            ,
            
        support_email: data.support_email
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await stores.setOwner( data.owner || null, {
            transaction,
        });
        
        await stores.setPrimary_address( data.primary_address || null, {
            transaction,
        });
        
        await stores.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

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

        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
            ,
            
                store_slug: item.store_slug
            ||
            null
            ,
            
                store_type: item.store_type
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                description: item.description
            ||
            null
            ,
            
                support_phone: item.support_phone
            ||
            null
            ,
            
                support_email: item.support_email
            ||
            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
        
        for (let i = 0; i < stores.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.stores.getTableName(),
                    belongsToColumn: 'store_images',
                    belongsToId: stores[i].id,
                },
                data[i].store_images,
                options,
            );
        }
        

        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.store_slug !== undefined) updatePayload.store_slug = data.store_slug;
        
        
        if (data.store_type !== undefined) updatePayload.store_type = data.store_type;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        if (data.support_phone !== undefined) updatePayload.support_phone = data.support_phone;
        
        
        if (data.support_email !== undefined) updatePayload.support_email = data.support_email;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

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

        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.products_store = await stores.getProducts_store({
            transaction
        });
        
        
        output.orders_store = await stores.getOrders_store({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.affiliate_programs_producer_store = await stores.getAffiliate_programs_producer_store({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        output.owner = await stores.getOwner({
            transaction
        });
        
        
        output.store_images = await stores.getStore_images({
            transaction
        });
        
        
        output.primary_address = await stores.getPrimary_address({
            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.users,
        as: 'owner',
        
        where: filter.owner ? {
          [Op.or]: [
            { id: { [Op.in]: filter.owner.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.owner.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



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

    ];

        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.store_slug) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'stores',
                        'store_slug',
                        filter.store_slug,
                    ),
                };
            }
            
            if (filter.description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'stores',
                        'description',
                        filter.description,
                    ),
                };
            }
            
            if (filter.support_phone) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'stores',
                        'support_phone',
                        filter.support_phone,
                    ),
                };
            }
            
            if (filter.support_email) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'stores',
                        'support_email',
                        filter.support_email,
                    ),
                };
            }
            

            
            

            

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

            
            if (filter.store_type) {
                where = {
                    ...where,
                store_type: filter.store_type,
            };
            }
            
            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.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,
        }));
    }

    
};

