
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const { resolveCurrencyId } = require('./defaultCurrency');



const Sequelize = db.Sequelize;
const Op = Sequelize.Op;

module.exports = class ContactsDBApi {
    

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

        const contacts = await db.contacts.create(
            {
                id: data.id || undefined,
        
        contact_type: data.contact_type
        ||
        null
            ,
            
        display_name: data.display_name
        ||
        null
            ,
            
        company_name: data.company_name
        ||
        null
            ,
            
        first_name: data.first_name
        ||
        null
            ,
            
        last_name: data.last_name
        ||
        null
            ,
            
        email: data.email
        ||
        null
            ,
            
        phone: data.phone
        ||
        null
            ,
            
        billing_address: data.billing_address
        ||
        null
            ,
            
        shipping_address: data.shipping_address
        ||
        null
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await contacts.setOrganization(currentUser.organization.id || null, {
            transaction,
        });
        const currencyId = await resolveCurrencyId(db, data.currency, transaction);
        await contacts.setCurrency(currencyId, {
            transaction,
        });
        
        await contacts.setDefault_tax_rate( data.default_tax_rate || null, {
            transaction,
        });
        

        

        

        return contacts;
    }
    

    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 contactsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                contact_type: item.contact_type
            ||
            null
            ,
            
                display_name: item.display_name
            ||
            null
            ,
            
                company_name: item.company_name
            ||
            null
            ,
            
                first_name: item.first_name
            ||
            null
            ,
            
                last_name: item.last_name
            ||
            null
            ,
            
                email: item.email
            ||
            null
            ,
            
                phone: item.phone
            ||
            null
            ,
            
                billing_address: item.billing_address
            ||
            null
            ,
            
                shipping_address: item.shipping_address
            ||
            null
            ,
            
                is_active: item.is_active
            ||
            false
        
            ,
            
                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 contacts = await db.contacts.bulkCreate(contactsData, { transaction });

        // For each item created, replace relation files
        

        return contacts;
    }

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


        

        const updatePayload = {};
        
        if (data.contact_type !== undefined) updatePayload.contact_type = data.contact_type;
        
        
        if (data.display_name !== undefined) updatePayload.display_name = data.display_name;
        
        
        if (data.company_name !== undefined) updatePayload.company_name = data.company_name;
        
        
        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.billing_address !== undefined) updatePayload.billing_address = data.billing_address;
        
        
        if (data.shipping_address !== undefined) updatePayload.shipping_address = data.shipping_address;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.organization !== undefined) {
            await contacts.setOrganization(
              
              (globalAccess ? data.organization : currentUser.organization.id),
              
              { transaction }
            );
        }
        
        if (data.currency !== undefined) {
            await contacts.setCurrency(
              
              data.currency,
              
              { transaction }
            );
        }
        
        if (data.default_tax_rate !== undefined) {
            await contacts.setDefault_tax_rate(
              
              data.default_tax_rate,
              
              { transaction }
            );
        }
        

        
        

        

        return contacts;
    }

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

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

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


        return contacts;
    }

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

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

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

        await contacts.destroy({
            transaction
        });

        return contacts;
    }

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

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

        if (!contacts) {
            return contacts;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        output.quotes_customer = await contacts.getQuotes_customer({
            transaction
        });
        
        
        
        output.invoices_customer = await contacts.getInvoices_customer({
            transaction
        });
        
        
        
        output.bills_supplier = await contacts.getBills_supplier({
            transaction
        });
        
        
        
        output.expenses_contact = await contacts.getExpenses_contact({
            transaction
        });
        
        
        
        
        output.payments_contact = await contacts.getPayments_contact({
            transaction
        });
        
        
        
        output.journal_lines_contact = await contacts.getJournal_lines_contact({
            transaction
        });
        
        
        output.documents_contact = await contacts.getDocuments_contact({
            transaction
        });
        
        
        
        
        output.organization = await contacts.getOrganization({
            transaction
        });
        
        
        output.currency = await contacts.getCurrency({
            transaction
        });
        
        
        output.default_tax_rate = await contacts.getDefault_tax_rate({
            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.organizations,
        as: 'organization',
        
      },

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

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



    ];

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

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

            
            

            

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

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


      
      if (filter.organization) {
        const listItems = filter.organization.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          organizationId: {[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.contacts.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(
                        'contacts',
                        'display_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

