
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,
        
        customer_code: data.customer_code
        ||
        null
            ,
            
        preferred_contact_channel: data.preferred_contact_channel
        ||
        null
            ,
            
        accepts_marketing: data.accepts_marketing
        ||
        false
        
            ,
            
        company_name: data.company_name
        ||
        null
            ,
            
        tax_identifier: data.tax_identifier
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await customers.setUser( data.user || 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,
                
                customer_code: item.customer_code
            ||
            null
            ,
            
                preferred_contact_channel: item.preferred_contact_channel
            ||
            null
            ,
            
                accepts_marketing: item.accepts_marketing
            ||
            false
        
            ,
            
                company_name: item.company_name
            ||
            null
            ,
            
                tax_identifier: item.tax_identifier
            ||
            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 customers = await db.customers.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.customer_code !== undefined) updatePayload.customer_code = data.customer_code;
        
        
        if (data.preferred_contact_channel !== undefined) updatePayload.preferred_contact_channel = data.preferred_contact_channel;
        
        
        if (data.accepts_marketing !== undefined) updatePayload.accepts_marketing = data.accepts_marketing;
        
        
        if (data.company_name !== undefined) updatePayload.company_name = data.company_name;
        
        
        if (data.tax_identifier !== undefined) updatePayload.tax_identifier = data.tax_identifier;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.user !== undefined) {
            await customers.setUser(
              
              data.user,
              
              { 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.devices_customer = await customers.getDevices_customer({
            transaction
        });
        
        
        output.repair_orders_customer = await customers.getRepair_orders_customer({
            transaction
        });
        
        
        
        
        
        
        output.invoices_customer = await customers.getInvoices_customer({
            transaction
        });
        
        
        
        
        output.ai_chat_sessions_customer = await customers.getAi_chat_sessions_customer({
            transaction
        });
        
        
        
        
        
        output.user = await customers.getUser({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        

        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

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



    ];

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

            
            if (filter.customer_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'customers',
                        'customer_code',
                        filter.customer_code,
                    ),
                };
            }
            
            if (filter.preferred_contact_channel) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'customers',
                        'preferred_contact_channel',
                        filter.preferred_contact_channel,
                    ),
                };
            }
            
            if (filter.company_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'customers',
                        'company_name',
                        filter.company_name,
                    ),
                };
            }
            
            if (filter.tax_identifier) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'customers',
                        'tax_identifier',
                        filter.tax_identifier,
                    ),
                };
            }
            

            
            

            

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

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


      



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

        

        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, ) {
        let where = {};
        
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'customers',
                        'customer_code',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

