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

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

        const capex_items = await db.capex_items.create(
            {
                id: data.id || undefined,
        
        cost_category: data.cost_category
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
        quantity: data.quantity
        ||
        null
            ,
            
        unit_cost: data.unit_cost
        ||
        null
            ,
            
        install_factor: data.install_factor
        ||
        null
            ,
            
        total_cost: data.total_cost
        ||
        null
            ,
            
        estimate_class: data.estimate_class
        ||
        null
            ,
            
        basis_notes: data.basis_notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await capex_items.setEconomic_model( data.economic_model || null, {
            transaction,
        });
        
        await capex_items.setEquipment_item( data.equipment_item || null, {
            transaction,
        });
        
        await capex_items.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return capex_items;
    }
    

    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 capex_itemsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                cost_category: item.cost_category
            ||
            null
            ,
            
                description: item.description
            ||
            null
            ,
            
                quantity: item.quantity
            ||
            null
            ,
            
                unit_cost: item.unit_cost
            ||
            null
            ,
            
                install_factor: item.install_factor
            ||
            null
            ,
            
                total_cost: item.total_cost
            ||
            null
            ,
            
                estimate_class: item.estimate_class
            ||
            null
            ,
            
                basis_notes: item.basis_notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return capex_items;
    }

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


        

        const updatePayload = {};
        
        if (data.cost_category !== undefined) updatePayload.cost_category = data.cost_category;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        if (data.quantity !== undefined) updatePayload.quantity = data.quantity;
        
        
        if (data.unit_cost !== undefined) updatePayload.unit_cost = data.unit_cost;
        
        
        if (data.install_factor !== undefined) updatePayload.install_factor = data.install_factor;
        
        
        if (data.total_cost !== undefined) updatePayload.total_cost = data.total_cost;
        
        
        if (data.estimate_class !== undefined) updatePayload.estimate_class = data.estimate_class;
        
        
        if (data.basis_notes !== undefined) updatePayload.basis_notes = data.basis_notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.economic_model !== undefined) {
            await capex_items.setEconomic_model(
              
              data.economic_model,
              
              { transaction }
            );
        }
        
        if (data.equipment_item !== undefined) {
            await capex_items.setEquipment_item(
              
              data.equipment_item,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await capex_items.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return capex_items;
    }

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

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

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


        return capex_items;
    }

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

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

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

        await capex_items.destroy({
            transaction
        });

        return capex_items;
    }

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

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

        if (!capex_items) {
            return capex_items;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.economic_model = await capex_items.getEconomic_model({
            transaction
        });
        
        
        output.equipment_item = await capex_items.getEquipment_item({
            transaction
        });
        
        
        output.organizations = await capex_items.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.economic_models,
        as: 'economic_model',
        
        where: filter.economic_model ? {
          [Op.or]: [
            { id: { [Op.in]: filter.economic_model.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.economic_model.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.equipment_items,
        as: 'equipment_item',
        
        where: filter.equipment_item ? {
          [Op.or]: [
            { id: { [Op.in]: filter.equipment_item.split('|').map(term => Utils.uuid(term)) } },
            {
              model: {
                [Op.or]: filter.equipment_item.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.cost_category) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'capex_items',
                        'cost_category',
                        filter.cost_category,
                    ),
                };
            }
            
            if (filter.description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'capex_items',
                        'description',
                        filter.description,
                    ),
                };
            }
            
            if (filter.basis_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'capex_items',
                        'basis_notes',
                        filter.basis_notes,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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


      

      

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

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

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

    
};

