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

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

        const merch_stores = await db.merch_stores.create(
            {
                id: data.id || undefined,
        
        store_name: data.store_name
        ||
        null
            ,
            
        store_description: data.store_description
        ||
        null
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
        policies_text: data.policies_text
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await merch_stores.setCreator( data.creator || null, {
            transaction,
        });
        
        await merch_stores.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

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

        return merch_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 merch_storesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                store_name: item.store_name
            ||
            null
            ,
            
                store_description: item.store_description
            ||
            null
            ,
            
                is_active: item.is_active
            ||
            false
        
            ,
            
                policies_text: item.policies_text
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

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


        

        const updatePayload = {};
        
        if (data.store_name !== undefined) updatePayload.store_name = data.store_name;
        
        
        if (data.store_description !== undefined) updatePayload.store_description = data.store_description;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        if (data.policies_text !== undefined) updatePayload.policies_text = data.policies_text;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

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

        return merch_stores;
    }

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

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

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


        return merch_stores;
    }

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

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

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

        await merch_stores.destroy({
            transaction
        });

        return merch_stores;
    }

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

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

        if (!merch_stores) {
            return merch_stores;
        }

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

        
        
        
        
        
        output.creator_profiles_merch_store = await merch_stores.getCreator_profiles_merch_store({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.products_merch_store = await merch_stores.getProducts_merch_store({
            transaction
        });
        
        
        
        output.orders_merch_store = await merch_stores.getOrders_merch_store({
            transaction
        });
        
        
        
        output.shipping_profiles_merch_store = await merch_stores.getShipping_profiles_merch_store({
            transaction
        });
        
        
        
        
        
        
        
        
        output.creator = await merch_stores.getCreator({
            transaction
        });
        
        
        output.logo_images = await merch_stores.getLogo_images({
            transaction
        });
        
        
        output.banner_images = await merch_stores.getBanner_images({
            transaction
        });
        
        
        output.organizations = await merch_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.creator_profiles,
        as: 'creator',
        
        where: filter.creator ? {
          [Op.or]: [
            { id: { [Op.in]: filter.creator.split('|').map(term => Utils.uuid(term)) } },
            {
              handle: {
                [Op.or]: filter.creator.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.store_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'merch_stores',
                        'store_name',
                        filter.store_name,
                    ),
                };
            }
            
            if (filter.store_description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'merch_stores',
                        'store_description',
                        filter.store_description,
                    ),
                };
            }
            
            if (filter.policies_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'merch_stores',
                        'policies_text',
                        filter.policies_text,
                    ),
                };
            }
            

            
            

            

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

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

    
};

