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

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

        const customers = await db.customers.create(
            {
                id: data.id || undefined,
        
        first_name: data.first_name
        ||
        null
            ,
            
        last_name: data.last_name
        ||
        null
            ,
            
        email: data.email
        ||
        null
            ,
            
        phone: data.phone
        ||
        null
            ,
            
        customer_state: data.customer_state
        ||
        null
            ,
            
        created_on_shopify_at: data.created_on_shopify_at
        ||
        null
            ,
            
        orders_count: data.orders_count
        ||
        null
            ,
            
        total_spent: data.total_spent
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await customers.setStore( data.store || null, {
            transaction,
        });
        
        await customers.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return customers;
    }
    

    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 customersData = data.map((item, index) => ({
                id: item.id || undefined,
                
                first_name: item.first_name
            ||
            null
            ,
            
                last_name: item.last_name
            ||
            null
            ,
            
                email: item.email
            ||
            null
            ,
            
                phone: item.phone
            ||
            null
            ,
            
                customer_state: item.customer_state
            ||
            null
            ,
            
                created_on_shopify_at: item.created_on_shopify_at
            ||
            null
            ,
            
                orders_count: item.orders_count
            ||
            null
            ,
            
                total_spent: item.total_spent
            ||
            null
            ,
            
                notes: item.notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return customers;
    }

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


        

        const updatePayload = {};
        
        if (data.first_name !== undefined) updatePayload.first_name = data.first_name;
        
        
        if (data.last_name !== undefined) updatePayload.last_name = data.last_name;
        
        
        if (data.email !== undefined) updatePayload.email = data.email;
        
        
        if (data.phone !== undefined) updatePayload.phone = data.phone;
        
        
        if (data.customer_state !== undefined) updatePayload.customer_state = data.customer_state;
        
        
        if (data.created_on_shopify_at !== undefined) updatePayload.created_on_shopify_at = data.created_on_shopify_at;
        
        
        if (data.orders_count !== undefined) updatePayload.orders_count = data.orders_count;
        
        
        if (data.total_spent !== undefined) updatePayload.total_spent = data.total_spent;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return customers;
    }

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

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

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


        return customers;
    }

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

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

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

        await customers.destroy({
            transaction
        });

        return customers;
    }

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

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

        if (!customers) {
            return customers;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        output.addresses_customer = await customers.getAddresses_customer({
            transaction
        });
        
        
        output.orders_customer = await customers.getOrders_customer({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        output.chat_sessions_customer = await customers.getChat_sessions_customer({
            transaction
        });
        
        
        
        output.support_tickets_customer = await customers.getSupport_tickets_customer({
            transaction
        });
        
        
        
        
        output.store = await customers.getStore({
            transaction
        });
        
        
        output.organizations = await customers.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.stores,
        as: 'store',
        
        where: filter.store ? {
          [Op.or]: [
            { id: { [Op.in]: filter.store.split('|').map(term => Utils.uuid(term)) } },
            {
              store_name: {
                [Op.or]: filter.store.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

            
            if (filter.first_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'customers',
                        'first_name',
                        filter.first_name,
                    ),
                };
            }
            
            if (filter.last_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'customers',
                        'last_name',
                        filter.last_name,
                    ),
                };
            }
            
            if (filter.email) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'customers',
                        'email',
                        filter.email,
                    ),
                };
            }
            
            if (filter.phone) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'customers',
                        'phone',
                        filter.phone,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'customers',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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


      

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

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

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

    
};

