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

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

        const ir_companies = await db.ir_companies.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        website: data.website
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
        hq_location: data.hq_location
        ||
        null
            ,
            
        last_updated_at: data.last_updated_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await ir_companies.setMarket_symbol( data.market_symbol || null, {
            transaction,
        });
        

        

        

        return ir_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 ir_companiesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                website: item.website
            ||
            null
            ,
            
                description: item.description
            ||
            null
            ,
            
                hq_location: item.hq_location
            ||
            null
            ,
            
                last_updated_at: item.last_updated_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return ir_companies;
    }

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

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.website !== undefined) updatePayload.website = data.website;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        if (data.hq_location !== undefined) updatePayload.hq_location = data.hq_location;
        
        
        if (data.last_updated_at !== undefined) updatePayload.last_updated_at = data.last_updated_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.market_symbol !== undefined) {
            await ir_companies.setMarket_symbol(
              
              data.market_symbol,
              
              { transaction }
            );
        }
        

        
        

        

        return ir_companies;
    }

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

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

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


        return ir_companies;
    }

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

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

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

        await ir_companies.destroy({
            transaction
        });

        return ir_companies;
    }

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

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

        if (!ir_companies) {
            return ir_companies;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.ir_management_members_ir_company = await ir_companies.getIr_management_members_ir_company({
            transaction
        });
        
        
        output.ir_filings_ir_company = await ir_companies.getIr_filings_ir_company({
            transaction
        });
        
        
        output.ir_dividends_ir_company = await ir_companies.getIr_dividends_ir_company({
            transaction
        });
        
        
        output.ir_announcements_ir_company = await ir_companies.getIr_announcements_ir_company({
            transaction
        });
        
        
        output.ir_financial_statement_summaries_ir_company = await ir_companies.getIr_financial_statement_summaries_ir_company({
            transaction
        });
        
        
        
        
        output.market_symbol = await ir_companies.getMarket_symbol({
            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.market_symbols,
        as: 'market_symbol',
        
        where: filter.market_symbol ? {
          [Op.or]: [
            { id: { [Op.in]: filter.market_symbol.split('|').map(term => Utils.uuid(term)) } },
            {
              symbol: {
                [Op.or]: filter.market_symbol.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'ir_companies',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.website) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'ir_companies',
                        'website',
                        filter.website,
                    ),
                };
            }
            
            if (filter.description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'ir_companies',
                        'description',
                        filter.description,
                    ),
                };
            }
            
            if (filter.hq_location) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'ir_companies',
                        'hq_location',
                        filter.hq_location,
                    ),
                };
            }
            

            
            

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

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

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

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

            


      



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

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

    
};

