
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,
        
        name: data.name
        ||
        null
            ,
            
        legal_name: data.legal_name
        ||
        null
            ,
            
        tax_number: data.tax_number
        ||
        null
            ,
            
        vat_number: data.vat_number
        ||
        null
            ,
            
        eori_number: data.eori_number
        ||
        null
            ,
            
        email: data.email
        ||
        null
            ,
            
        phone: data.phone
        ||
        null
            ,
            
        phone2: data.phone2
        ||
        null
            ,
            
        website: data.website
        ||
        null
            ,
            
        address_line1: data.address_line1
        ||
        null
            ,
            
        address_line2: data.address_line2
        ||
        null
            ,
            
        postal_code: data.postal_code
        ||
        null
            ,
            
        city: data.city
        ||
        null
            ,
            
        country_code: data.country_code
        ||
        null
            ,
            
        payment_terms_days: data.payment_terms_days
        ||
        null
            ,
            
        currency: data.currency
        ||
        null
            ,
            
        credit_limit_eur: data.credit_limit_eur
        ||
        null
            ,
            
        contact_person: data.contact_person
        ||
        null
            ,
            
        contact_email: data.contact_email
        ||
        null
            ,
            
        contact_phone: data.contact_phone
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await customers.setCompany( data.company || null, {
            transaction,
        });
        

        

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

        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,
                
                name: item.name
            ||
            null
            ,
            
                legal_name: item.legal_name
            ||
            null
            ,
            
                tax_number: item.tax_number
            ||
            null
            ,
            
                vat_number: item.vat_number
            ||
            null
            ,
            
                eori_number: item.eori_number
            ||
            null
            ,
            
                email: item.email
            ||
            null
            ,
            
                phone: item.phone
            ||
            null
            ,
            
                phone2: item.phone2
            ||
            null
            ,
            
                website: item.website
            ||
            null
            ,
            
                address_line1: item.address_line1
            ||
            null
            ,
            
                address_line2: item.address_line2
            ||
            null
            ,
            
                postal_code: item.postal_code
            ||
            null
            ,
            
                city: item.city
            ||
            null
            ,
            
                country_code: item.country_code
            ||
            null
            ,
            
                payment_terms_days: item.payment_terms_days
            ||
            null
            ,
            
                currency: item.currency
            ||
            null
            ,
            
                credit_limit_eur: item.credit_limit_eur
            ||
            null
            ,
            
                contact_person: item.contact_person
            ||
            null
            ,
            
                contact_email: item.contact_email
            ||
            null
            ,
            
                contact_phone: item.contact_phone
            ||
            null
            ,
            
                notes: item.notes
            ||
            null
            ,
            
                is_active: item.is_active
            ||
            false
        
            ,
            
            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
        
        for (let i = 0; i < customers.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.customers.getTableName(),
                    belongsToColumn: 'logo',
                    belongsToId: customers[i].id,
                },
                data[i].logo,
                options,
            );
        }
        

        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.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.legal_name !== undefined) updatePayload.legal_name = data.legal_name;
        
        
        if (data.tax_number !== undefined) updatePayload.tax_number = data.tax_number;
        
        
        if (data.vat_number !== undefined) updatePayload.vat_number = data.vat_number;
        
        
        if (data.eori_number !== undefined) updatePayload.eori_number = data.eori_number;
        
        
        if (data.email !== undefined) updatePayload.email = data.email;
        
        
        if (data.phone !== undefined) updatePayload.phone = data.phone;
        
        
        if (data.phone2 !== undefined) updatePayload.phone2 = data.phone2;
        
        
        if (data.website !== undefined) updatePayload.website = data.website;
        
        
        if (data.address_line1 !== undefined) updatePayload.address_line1 = data.address_line1;
        
        
        if (data.address_line2 !== undefined) updatePayload.address_line2 = data.address_line2;
        
        
        if (data.postal_code !== undefined) updatePayload.postal_code = data.postal_code;
        
        
        if (data.city !== undefined) updatePayload.city = data.city;
        
        
        if (data.country_code !== undefined) updatePayload.country_code = data.country_code;
        
        
        if (data.payment_terms_days !== undefined) updatePayload.payment_terms_days = data.payment_terms_days;
        
        
        if (data.currency !== undefined) updatePayload.currency = data.currency;
        
        
        if (data.credit_limit_eur !== undefined) updatePayload.credit_limit_eur = data.credit_limit_eur;
        
        
        if (data.contact_person !== undefined) updatePayload.contact_person = data.contact_person;
        
        
        if (data.contact_email !== undefined) updatePayload.contact_email = data.contact_email;
        
        
        if (data.contact_phone !== undefined) updatePayload.contact_phone = data.contact_phone;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.company !== undefined) {
            await customers.setCompany(
              
              data.company,
              
              { transaction }
            );
        }
        

        
        

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

        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.orders_customer = await customers.getOrders_customer({
            transaction
        });
        
        
        
        
        
        
        
        output.invoices_customer = await customers.getInvoices_customer({
            transaction
        });
        
        
        
        
        
        
        
        
        
        output.company = await customers.getCompany({
            transaction
        });
        
        
        output.logo = await customers.getLogo({
            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.companies,
        as: 'company',
        
        where: filter.company ? {
          [Op.or]: [
            { id: { [Op.in]: filter.company.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.company.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



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

    ];

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

            
            if (filter.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'customers',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.legal_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'customers',
                        'legal_name',
                        filter.legal_name,
                    ),
                };
            }
            
            if (filter.tax_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'customers',
                        'tax_number',
                        filter.tax_number,
                    ),
                };
            }
            
            if (filter.vat_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'customers',
                        'vat_number',
                        filter.vat_number,
                    ),
                };
            }
            
            if (filter.eori_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'customers',
                        'eori_number',
                        filter.eori_number,
                    ),
                };
            }
            
            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.phone2) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'customers',
                        'phone2',
                        filter.phone2,
                    ),
                };
            }
            
            if (filter.website) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'customers',
                        'website',
                        filter.website,
                    ),
                };
            }
            
            if (filter.address_line1) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'customers',
                        'address_line1',
                        filter.address_line1,
                    ),
                };
            }
            
            if (filter.address_line2) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'customers',
                        'address_line2',
                        filter.address_line2,
                    ),
                };
            }
            
            if (filter.postal_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'customers',
                        'postal_code',
                        filter.postal_code,
                    ),
                };
            }
            
            if (filter.city) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'customers',
                        'city',
                        filter.city,
                    ),
                };
            }
            
            if (filter.country_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'customers',
                        'country_code',
                        filter.country_code,
                    ),
                };
            }
            
            if (filter.contact_person) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'customers',
                        'contact_person',
                        filter.contact_person,
                    ),
                };
            }
            
            if (filter.contact_email) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'customers',
                        'contact_email',
                        filter.contact_email,
                    ),
                };
            }
            
            if (filter.contact_phone) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'customers',
                        'contact_phone',
                        filter.contact_phone,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'customers',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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


      



            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',
                        'name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

