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

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

        const merchants = await db.merchants.create(
            {
                id: data.id || undefined,
        
        business_name: data.business_name
        ||
        null
            ,
            
        legal_name: data.legal_name
        ||
        null
            ,
            
        tin_number: data.tin_number
        ||
        null
            ,
            
        vat_registration_number: data.vat_registration_number
        ||
        null
            ,
            
        taxpayer_type: data.taxpayer_type
        ||
        null
            ,
            
        industry: data.industry
        ||
        null
            ,
            
        city: data.city
        ||
        null
            ,
            
        address: data.address
        ||
        null
            ,
            
        contact_name: data.contact_name
        ||
        null
            ,
            
        contact_phone: data.contact_phone
        ||
        null
            ,
            
        contact_email: data.contact_email
        ||
        null
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
        onboarded_at: data.onboarded_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await merchants.setFirm( data.firm || null, {
            transaction,
        });
        
        await merchants.setAssigned_accountant( data.assigned_accountant || null, {
            transaction,
        });
        
        await merchants.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return merchants;
    }
    

    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 merchantsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                business_name: item.business_name
            ||
            null
            ,
            
                legal_name: item.legal_name
            ||
            null
            ,
            
                tin_number: item.tin_number
            ||
            null
            ,
            
                vat_registration_number: item.vat_registration_number
            ||
            null
            ,
            
                taxpayer_type: item.taxpayer_type
            ||
            null
            ,
            
                industry: item.industry
            ||
            null
            ,
            
                city: item.city
            ||
            null
            ,
            
                address: item.address
            ||
            null
            ,
            
                contact_name: item.contact_name
            ||
            null
            ,
            
                contact_phone: item.contact_phone
            ||
            null
            ,
            
                contact_email: item.contact_email
            ||
            null
            ,
            
                is_active: item.is_active
            ||
            false
        
            ,
            
                onboarded_at: item.onboarded_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return merchants;
    }

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


        

        const updatePayload = {};
        
        if (data.business_name !== undefined) updatePayload.business_name = data.business_name;
        
        
        if (data.legal_name !== undefined) updatePayload.legal_name = data.legal_name;
        
        
        if (data.tin_number !== undefined) updatePayload.tin_number = data.tin_number;
        
        
        if (data.vat_registration_number !== undefined) updatePayload.vat_registration_number = data.vat_registration_number;
        
        
        if (data.taxpayer_type !== undefined) updatePayload.taxpayer_type = data.taxpayer_type;
        
        
        if (data.industry !== undefined) updatePayload.industry = data.industry;
        
        
        if (data.city !== undefined) updatePayload.city = data.city;
        
        
        if (data.address !== undefined) updatePayload.address = data.address;
        
        
        if (data.contact_name !== undefined) updatePayload.contact_name = data.contact_name;
        
        
        if (data.contact_phone !== undefined) updatePayload.contact_phone = data.contact_phone;
        
        
        if (data.contact_email !== undefined) updatePayload.contact_email = data.contact_email;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        if (data.onboarded_at !== undefined) updatePayload.onboarded_at = data.onboarded_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.firm !== undefined) {
            await merchants.setFirm(
              
              data.firm,
              
              { transaction }
            );
        }
        
        if (data.assigned_accountant !== undefined) {
            await merchants.setAssigned_accountant(
              
              data.assigned_accountant,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await merchants.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return merchants;
    }

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

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

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


        return merchants;
    }

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

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

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

        await merchants.destroy({
            transaction
        });

        return merchants;
    }

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

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

        if (!merchants) {
            return merchants;
        }

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

        
        
        
        
        
        
        
        output.customers_merchant = await merchants.getCustomers_merchant({
            transaction
        });
        
        
        output.suppliers_merchant = await merchants.getSuppliers_merchant({
            transaction
        });
        
        
        output.products_merchant = await merchants.getProducts_merchant({
            transaction
        });
        
        
        output.receipts_merchant = await merchants.getReceipts_merchant({
            transaction
        });
        
        
        output.ocr_extractions_merchant = await merchants.getOcr_extractions_merchant({
            transaction
        });
        
        
        output.sales_invoices_merchant = await merchants.getSales_invoices_merchant({
            transaction
        });
        
        
        
        output.purchase_invoices_merchant = await merchants.getPurchase_invoices_merchant({
            transaction
        });
        
        
        
        output.expenses_merchant = await merchants.getExpenses_merchant({
            transaction
        });
        
        
        output.tax_periods_merchant = await merchants.getTax_periods_merchant({
            transaction
        });
        
        
        output.vat_declarations_merchant = await merchants.getVat_declarations_merchant({
            transaction
        });
        
        
        output.tot_declarations_merchant = await merchants.getTot_declarations_merchant({
            transaction
        });
        
        
        output.declaration_submissions_merchant = await merchants.getDeclaration_submissions_merchant({
            transaction
        });
        
        
        output.messages_merchant = await merchants.getMessages_merchant({
            transaction
        });
        
        
        output.audit_events_merchant = await merchants.getAudit_events_merchant({
            transaction
        });
        
        
        
        output.firm = await merchants.getFirm({
            transaction
        });
        
        
        output.assigned_accountant = await merchants.getAssigned_accountant({
            transaction
        });
        
        
        output.organizations = await merchants.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.firms,
        as: 'firm',
        
        where: filter.firm ? {
          [Op.or]: [
            { id: { [Op.in]: filter.firm.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.firm.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.users,
        as: 'assigned_accountant',
        
        where: filter.assigned_accountant ? {
          [Op.or]: [
            { id: { [Op.in]: filter.assigned_accountant.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.assigned_accountant.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.business_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'merchants',
                        'business_name',
                        filter.business_name,
                    ),
                };
            }
            
            if (filter.legal_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'merchants',
                        'legal_name',
                        filter.legal_name,
                    ),
                };
            }
            
            if (filter.tin_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'merchants',
                        'tin_number',
                        filter.tin_number,
                    ),
                };
            }
            
            if (filter.vat_registration_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'merchants',
                        'vat_registration_number',
                        filter.vat_registration_number,
                    ),
                };
            }
            
            if (filter.city) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'merchants',
                        'city',
                        filter.city,
                    ),
                };
            }
            
            if (filter.address) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'merchants',
                        'address',
                        filter.address,
                    ),
                };
            }
            
            if (filter.contact_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'merchants',
                        'contact_name',
                        filter.contact_name,
                    ),
                };
            }
            
            if (filter.contact_phone) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'merchants',
                        'contact_phone',
                        filter.contact_phone,
                    ),
                };
            }
            
            if (filter.contact_email) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'merchants',
                        'contact_email',
                        filter.contact_email,
                    ),
                };
            }
            

            
            

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

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

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

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

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


      

      

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

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

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

    
};

