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

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

        const companies = await db.companies.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        short_name: data.short_name
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        legal_name: data.legal_name
        ||
        null
            ,
            
        legal_form: data.legal_form
        ||
        null
            ,
            
        handelsregister_number: data.handelsregister_number
        ||
        null
            ,
            
        register_court: data.register_court
        ||
        null
            ,
            
        managing_directors: data.managing_directors
        ||
        null
            ,
            
        founding_date: data.founding_date
        ||
        null
            ,
            
        vat_number: data.vat_number
        ||
        null
            ,
            
        tax_number: data.tax_number
        ||
        null
            ,
            
        vat_status: data.vat_status
        ||
        null
            ,
            
        eori_number: data.eori_number
        ||
        null
            ,
            
        gln_number: data.gln_number
        ||
        null
            ,
            
        scac: data.scac
        ||
        null
            ,
            
        address_line1: data.address_line1
        ||
        null
            ,
            
        address_line2: data.address_line2
        ||
        null
            ,
            
        postal_code: data.postal_code
        ||
        null
            ,
            
        city: data.city
        ||
        null
            ,
            
        state: data.state
        ||
        null
            ,
            
        country_code: data.country_code
        ||
        null
            ,
            
        email: data.email
        ||
        null
            ,
            
        phone: data.phone
        ||
        null
            ,
            
        website: data.website
        ||
        null
            ,
            
        dispatch_email: data.dispatch_email
        ||
        null
            ,
            
        accounting_email: data.accounting_email
        ||
        null
            ,
            
        hr_email: data.hr_email
        ||
        null
            ,
            
        default_currency: data.default_currency
        ||
        null
            ,
            
        invoice_prefix: data.invoice_prefix
        ||
        null
            ,
            
        invoice_numbering_mode: data.invoice_numbering_mode
        ||
        null
            ,
            
        invoice_next_number: data.invoice_next_number
        ||
        null
            ,
            
        invoice_rounding: data.invoice_rounding
        ||
        null
            ,
            
        payment_terms_days: data.payment_terms_days
        ||
        null
            ,
            
        payroll_provider: data.payroll_provider
        ||
        null
            ,
            
        payroll_contact_email: data.payroll_contact_email
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        

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

        return companies;
    }
    

    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 companiesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                short_name: item.short_name
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                legal_name: item.legal_name
            ||
            null
            ,
            
                legal_form: item.legal_form
            ||
            null
            ,
            
                handelsregister_number: item.handelsregister_number
            ||
            null
            ,
            
                register_court: item.register_court
            ||
            null
            ,
            
                managing_directors: item.managing_directors
            ||
            null
            ,
            
                founding_date: item.founding_date
            ||
            null
            ,
            
                vat_number: item.vat_number
            ||
            null
            ,
            
                tax_number: item.tax_number
            ||
            null
            ,
            
                vat_status: item.vat_status
            ||
            null
            ,
            
                eori_number: item.eori_number
            ||
            null
            ,
            
                gln_number: item.gln_number
            ||
            null
            ,
            
                scac: item.scac
            ||
            null
            ,
            
                address_line1: item.address_line1
            ||
            null
            ,
            
                address_line2: item.address_line2
            ||
            null
            ,
            
                postal_code: item.postal_code
            ||
            null
            ,
            
                city: item.city
            ||
            null
            ,
            
                state: item.state
            ||
            null
            ,
            
                country_code: item.country_code
            ||
            null
            ,
            
                email: item.email
            ||
            null
            ,
            
                phone: item.phone
            ||
            null
            ,
            
                website: item.website
            ||
            null
            ,
            
                dispatch_email: item.dispatch_email
            ||
            null
            ,
            
                accounting_email: item.accounting_email
            ||
            null
            ,
            
                hr_email: item.hr_email
            ||
            null
            ,
            
                default_currency: item.default_currency
            ||
            null
            ,
            
                invoice_prefix: item.invoice_prefix
            ||
            null
            ,
            
                invoice_numbering_mode: item.invoice_numbering_mode
            ||
            null
            ,
            
                invoice_next_number: item.invoice_next_number
            ||
            null
            ,
            
                invoice_rounding: item.invoice_rounding
            ||
            null
            ,
            
                payment_terms_days: item.payment_terms_days
            ||
            null
            ,
            
                payroll_provider: item.payroll_provider
            ||
            null
            ,
            
                payroll_contact_email: item.payroll_contact_email
            ||
            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 companies = await db.companies.bulkCreate(companiesData, { transaction });

        // For each item created, replace relation files
        
        for (let i = 0; i < companies.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.companies.getTableName(),
                    belongsToColumn: 'logo',
                    belongsToId: companies[i].id,
                },
                data[i].logo,
                options,
            );
        }
        

        return companies;
    }

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

        const companies = await db.companies.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.short_name !== undefined) updatePayload.short_name = data.short_name;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.legal_name !== undefined) updatePayload.legal_name = data.legal_name;
        
        
        if (data.legal_form !== undefined) updatePayload.legal_form = data.legal_form;
        
        
        if (data.handelsregister_number !== undefined) updatePayload.handelsregister_number = data.handelsregister_number;
        
        
        if (data.register_court !== undefined) updatePayload.register_court = data.register_court;
        
        
        if (data.managing_directors !== undefined) updatePayload.managing_directors = data.managing_directors;
        
        
        if (data.founding_date !== undefined) updatePayload.founding_date = data.founding_date;
        
        
        if (data.vat_number !== undefined) updatePayload.vat_number = data.vat_number;
        
        
        if (data.tax_number !== undefined) updatePayload.tax_number = data.tax_number;
        
        
        if (data.vat_status !== undefined) updatePayload.vat_status = data.vat_status;
        
        
        if (data.eori_number !== undefined) updatePayload.eori_number = data.eori_number;
        
        
        if (data.gln_number !== undefined) updatePayload.gln_number = data.gln_number;
        
        
        if (data.scac !== undefined) updatePayload.scac = data.scac;
        
        
        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.state !== undefined) updatePayload.state = data.state;
        
        
        if (data.country_code !== undefined) updatePayload.country_code = data.country_code;
        
        
        if (data.email !== undefined) updatePayload.email = data.email;
        
        
        if (data.phone !== undefined) updatePayload.phone = data.phone;
        
        
        if (data.website !== undefined) updatePayload.website = data.website;
        
        
        if (data.dispatch_email !== undefined) updatePayload.dispatch_email = data.dispatch_email;
        
        
        if (data.accounting_email !== undefined) updatePayload.accounting_email = data.accounting_email;
        
        
        if (data.hr_email !== undefined) updatePayload.hr_email = data.hr_email;
        
        
        if (data.default_currency !== undefined) updatePayload.default_currency = data.default_currency;
        
        
        if (data.invoice_prefix !== undefined) updatePayload.invoice_prefix = data.invoice_prefix;
        
        
        if (data.invoice_numbering_mode !== undefined) updatePayload.invoice_numbering_mode = data.invoice_numbering_mode;
        
        
        if (data.invoice_next_number !== undefined) updatePayload.invoice_next_number = data.invoice_next_number;
        
        
        if (data.invoice_rounding !== undefined) updatePayload.invoice_rounding = data.invoice_rounding;
        
        
        if (data.payment_terms_days !== undefined) updatePayload.payment_terms_days = data.payment_terms_days;
        
        
        if (data.payroll_provider !== undefined) updatePayload.payroll_provider = data.payroll_provider;
        
        
        if (data.payroll_contact_email !== undefined) updatePayload.payroll_contact_email = data.payroll_contact_email;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        

        
        

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

        return companies;
    }

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

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

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


        return companies;
    }

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

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

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

        await companies.destroy({
            transaction
        });

        return companies;
    }

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

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

        if (!companies) {
            return companies;
        }

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

        
        
        
        
        
        output.company_locations_company = await companies.getCompany_locations_company({
            transaction
        });
        
        
        output.company_contacts_company = await companies.getCompany_contacts_company({
            transaction
        });
        
        
        output.company_bank_accounts_company = await companies.getCompany_bank_accounts_company({
            transaction
        });
        
        
        output.company_permits_company = await companies.getCompany_permits_company({
            transaction
        });
        
        
        output.company_insurances_company = await companies.getCompany_insurances_company({
            transaction
        });
        
        
        output.company_documents_company = await companies.getCompany_documents_company({
            transaction
        });
        
        
        
        output.employees_company = await companies.getEmployees_company({
            transaction
        });
        
        
        
        
        
        
        output.incidents_company = await companies.getIncidents_company({
            transaction
        });
        
        
        output.documents_company = await companies.getDocuments_company({
            transaction
        });
        
        
        
        output.document_retention_policies_company = await companies.getDocument_retention_policies_company({
            transaction
        });
        
        
        output.customers_company = await companies.getCustomers_company({
            transaction
        });
        
        
        output.vendors_company = await companies.getVendors_company({
            transaction
        });
        
        
        output.vehicles_company = await companies.getVehicles_company({
            transaction
        });
        
        
        output.trailers_company = await companies.getTrailers_company({
            transaction
        });
        
        
        output.vehicle_trailer_links_company = await companies.getVehicle_trailer_links_company({
            transaction
        });
        
        
        output.vehicle_inspections_company = await companies.getVehicle_inspections_company({
            transaction
        });
        
        
        output.vehicle_maintenances_company = await companies.getVehicle_maintenances_company({
            transaction
        });
        
        
        output.vehicle_insurances_company = await companies.getVehicle_insurances_company({
            transaction
        });
        
        
        output.vehicle_documents_company = await companies.getVehicle_documents_company({
            transaction
        });
        
        
        
        output.driver_vehicle_assignments_company = await companies.getDriver_vehicle_assignments_company({
            transaction
        });
        
        
        output.orders_company = await companies.getOrders_company({
            transaction
        });
        
        
        output.loads_company = await companies.getLoads_company({
            transaction
        });
        
        
        output.load_stops_company = await companies.getLoad_stops_company({
            transaction
        });
        
        
        output.trips_company = await companies.getTrips_company({
            transaction
        });
        
        
        
        output.pod_files_company = await companies.getPod_files_company({
            transaction
        });
        
        
        output.invoices_company = await companies.getInvoices_company({
            transaction
        });
        
        
        
        output.payments_company = await companies.getPayments_company({
            transaction
        });
        
        
        output.cost_items_company = await companies.getCost_items_company({
            transaction
        });
        
        
        
        
        
        
        output.logo = await companies.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.file,
        as: 'logo',
      },

    ];

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

            
            if (filter.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'companies',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.short_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'companies',
                        'short_name',
                        filter.short_name,
                    ),
                };
            }
            
            if (filter.legal_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'companies',
                        'legal_name',
                        filter.legal_name,
                    ),
                };
            }
            
            if (filter.handelsregister_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'companies',
                        'handelsregister_number',
                        filter.handelsregister_number,
                    ),
                };
            }
            
            if (filter.register_court) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'companies',
                        'register_court',
                        filter.register_court,
                    ),
                };
            }
            
            if (filter.managing_directors) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'companies',
                        'managing_directors',
                        filter.managing_directors,
                    ),
                };
            }
            
            if (filter.vat_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'companies',
                        'vat_number',
                        filter.vat_number,
                    ),
                };
            }
            
            if (filter.tax_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'companies',
                        'tax_number',
                        filter.tax_number,
                    ),
                };
            }
            
            if (filter.eori_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'companies',
                        'eori_number',
                        filter.eori_number,
                    ),
                };
            }
            
            if (filter.gln_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'companies',
                        'gln_number',
                        filter.gln_number,
                    ),
                };
            }
            
            if (filter.scac) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'companies',
                        'scac',
                        filter.scac,
                    ),
                };
            }
            
            if (filter.address_line1) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'companies',
                        'address_line1',
                        filter.address_line1,
                    ),
                };
            }
            
            if (filter.address_line2) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'companies',
                        'address_line2',
                        filter.address_line2,
                    ),
                };
            }
            
            if (filter.postal_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'companies',
                        'postal_code',
                        filter.postal_code,
                    ),
                };
            }
            
            if (filter.city) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'companies',
                        'city',
                        filter.city,
                    ),
                };
            }
            
            if (filter.state) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'companies',
                        'state',
                        filter.state,
                    ),
                };
            }
            
            if (filter.country_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'companies',
                        'country_code',
                        filter.country_code,
                    ),
                };
            }
            
            if (filter.email) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'companies',
                        'email',
                        filter.email,
                    ),
                };
            }
            
            if (filter.phone) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'companies',
                        'phone',
                        filter.phone,
                    ),
                };
            }
            
            if (filter.website) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'companies',
                        'website',
                        filter.website,
                    ),
                };
            }
            
            if (filter.dispatch_email) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'companies',
                        'dispatch_email',
                        filter.dispatch_email,
                    ),
                };
            }
            
            if (filter.accounting_email) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'companies',
                        'accounting_email',
                        filter.accounting_email,
                    ),
                };
            }
            
            if (filter.hr_email) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'companies',
                        'hr_email',
                        filter.hr_email,
                    ),
                };
            }
            
            if (filter.invoice_prefix) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'companies',
                        'invoice_prefix',
                        filter.invoice_prefix,
                    ),
                };
            }
            
            if (filter.payroll_provider) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'companies',
                        'payroll_provider',
                        filter.payroll_provider,
                    ),
                };
            }
            
            if (filter.payroll_contact_email) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'companies',
                        'payroll_contact_email',
                        filter.payroll_contact_email,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'companies',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    invoice_next_number: {
                    ...where.invoice_next_number,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            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.active !== undefined) {
                where = {
                    ...where,
                    active: filter.active === true || filter.active === 'true'
                };
            }

            
            if (filter.status) {
                where = {
                    ...where,
                status: filter.status,
            };
            }
            
            if (filter.legal_form) {
                where = {
                    ...where,
                legal_form: filter.legal_form,
            };
            }
            
            if (filter.vat_status) {
                where = {
                    ...where,
                vat_status: filter.vat_status,
            };
            }
            
            if (filter.default_currency) {
                where = {
                    ...where,
                default_currency: filter.default_currency,
            };
            }
            
            if (filter.invoice_numbering_mode) {
                where = {
                    ...where,
                invoice_numbering_mode: filter.invoice_numbering_mode,
            };
            }
            
            if (filter.invoice_rounding) {
                where = {
                    ...where,
                invoice_rounding: filter.invoice_rounding,
            };
            }
            




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

        const records = await db.companies.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,
        }));
    }

    
};

