
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,
        
        legal_name: data.legal_name
        ||
        null
            ,
            
        trade_name: data.trade_name
        ||
        null
            ,
            
        registration_number: data.registration_number
        ||
        null
            ,
            
        tax_number: data.tax_number
        ||
        null
            ,
            
        currency_code: data.currency_code
        ||
        null
            ,
            
        timezone: data.timezone
        ||
        null
            ,
            
        support_email: data.support_email
        ||
        null
            ,
            
        support_phone: data.support_phone
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await companies.setOrganizations( data.organizations || null, {
            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,
                
                legal_name: item.legal_name
            ||
            null
            ,
            
                trade_name: item.trade_name
            ||
            null
            ,
            
                registration_number: item.registration_number
            ||
            null
            ,
            
                tax_number: item.tax_number
            ||
            null
            ,
            
                currency_code: item.currency_code
            ||
            null
            ,
            
                timezone: item.timezone
            ||
            null
            ,
            
                support_email: item.support_email
            ||
            null
            ,
            
                support_phone: item.support_phone
            ||
            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 globalAccess = currentUser.app_role?.globalAccess;

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


        

        const updatePayload = {};
        
        if (data.legal_name !== undefined) updatePayload.legal_name = data.legal_name;
        
        
        if (data.trade_name !== undefined) updatePayload.trade_name = data.trade_name;
        
        
        if (data.registration_number !== undefined) updatePayload.registration_number = data.registration_number;
        
        
        if (data.tax_number !== undefined) updatePayload.tax_number = data.tax_number;
        
        
        if (data.currency_code !== undefined) updatePayload.currency_code = data.currency_code;
        
        
        if (data.timezone !== undefined) updatePayload.timezone = data.timezone;
        
        
        if (data.support_email !== undefined) updatePayload.support_email = data.support_email;
        
        
        if (data.support_phone !== undefined) updatePayload.support_phone = data.support_phone;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.organizations !== undefined) {
            await companies.setOrganizations(
              
              data.organizations,
              
              { 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.branches_company = await companies.getBranches_company({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.logo = await companies.getLogo({
            transaction
        });
        
        
        output.organizations = await companies.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.organizations,
        as: 'organizations',
        
      },



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

    ];

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

            
            if (filter.legal_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'companies',
                        'legal_name',
                        filter.legal_name,
                    ),
                };
            }
            
            if (filter.trade_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'companies',
                        'trade_name',
                        filter.trade_name,
                    ),
                };
            }
            
            if (filter.registration_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'companies',
                        'registration_number',
                        filter.registration_number,
                    ),
                };
            }
            
            if (filter.tax_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'companies',
                        'tax_number',
                        filter.tax_number,
                    ),
                };
            }
            
            if (filter.currency_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'companies',
                        'currency_code',
                        filter.currency_code,
                    ),
                };
            }
            
            if (filter.timezone) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'companies',
                        'timezone',
                        filter.timezone,
                    ),
                };
            }
            
            if (filter.support_email) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'companies',
                        'support_email',
                        filter.support_email,
                    ),
                };
            }
            
            if (filter.support_phone) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'companies',
                        'support_phone',
                        filter.support_phone,
                    ),
                };
            }
            

            
            

            

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

            


      
      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.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,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

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

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

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

    
};

