
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_code: data.store_code
        ||
        null
            ,
            
        store_phone: data.store_phone
        ||
        null
            ,
            
        store_email: data.store_email
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        offers_pickup: data.offers_pickup
        ||
        false
        
            ,
            
        offers_delivery: data.offers_delivery
        ||
        false
        
            ,
            
        opened_at: data.opened_at
        ||
        null
            ,
            
        closed_at: data.closed_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await stores.setMerchant_profile( data.merchant_profile || null, {
            transaction,
        });
        
        await stores.setAddress( data.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_code: item.store_code
            ||
            null
            ,
            
                store_phone: item.store_phone
            ||
            null
            ,
            
                store_email: item.store_email
            ||
            null
            ,
            
                description: item.description
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                offers_pickup: item.offers_pickup
            ||
            false
        
            ,
            
                offers_delivery: item.offers_delivery
            ||
            false
        
            ,
            
                opened_at: item.opened_at
            ||
            null
            ,
            
                closed_at: item.closed_at
            ||
            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_code !== undefined) updatePayload.store_code = data.store_code;
        
        
        if (data.store_phone !== undefined) updatePayload.store_phone = data.store_phone;
        
        
        if (data.store_email !== undefined) updatePayload.store_email = data.store_email;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.offers_pickup !== undefined) updatePayload.offers_pickup = data.offers_pickup;
        
        
        if (data.offers_delivery !== undefined) updatePayload.offers_delivery = data.offers_delivery;
        
        
        if (data.opened_at !== undefined) updatePayload.opened_at = data.opened_at;
        
        
        if (data.closed_at !== undefined) updatePayload.closed_at = data.closed_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.merchant_profile !== undefined) {
            await stores.setMerchant_profile(
              
              data.merchant_profile,
              
              { transaction }
            );
        }
        
        if (data.address !== undefined) {
            await stores.setAddress(
              
              data.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.carts_store = await stores.getCarts_store({
            transaction
        });
        
        
        
        output.orders_store = await stores.getOrders_store({
            transaction
        });
        
        
        
        
        
        
        output.commissions_store = await stores.getCommissions_store({
            transaction
        });
        
        
        output.reviews_store = await stores.getReviews_store({
            transaction
        });
        
        
        
        
        
        
        
        
        output.merchant_profile = await stores.getMerchant_profile({
            transaction
        });
        
        
        output.store_images = await stores.getStore_images({
            transaction
        });
        
        
        output.address = await stores.getAddress({
            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.merchant_profiles,
        as: 'merchant_profile',
        
        where: filter.merchant_profile ? {
          [Op.or]: [
            { id: { [Op.in]: filter.merchant_profile.split('|').map(term => Utils.uuid(term)) } },
            {
              business_name: {
                [Op.or]: filter.merchant_profile.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.addresses,
        as: 'address',
        
        where: filter.address ? {
          [Op.or]: [
            { id: { [Op.in]: filter.address.split('|').map(term => Utils.uuid(term)) } },
            {
              label: {
                [Op.or]: filter.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_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'stores',
                        'store_code',
                        filter.store_code,
                    ),
                };
            }
            
            if (filter.store_phone) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'stores',
                        'store_phone',
                        filter.store_phone,
                    ),
                };
            }
            
            if (filter.store_email) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'stores',
                        'store_email',
                        filter.store_email,
                    ),
                };
            }
            
            if (filter.description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'stores',
                        'description',
                        filter.description,
                    ),
                };
            }
            

            
            

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    opened_at: {
                    ...where.opened_at,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.closed_atRange) {
                const [start, end] = filter.closed_atRange;

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

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

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

            
            if (filter.status) {
                where = {
                    ...where,
                status: filter.status,
            };
            }
            
            if (filter.offers_pickup) {
                where = {
                    ...where,
                offers_pickup: filter.offers_pickup,
            };
            }
            
            if (filter.offers_delivery) {
                where = {
                    ...where,
                offers_delivery: filter.offers_delivery,
            };
            }
            


      

      

      
      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,
        }));
    }

    
};

