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

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

        const assets = await db.assets.create(
            {
                id: data.id || undefined,
        
        asset_name: data.asset_name
        ||
        null
            ,
            
        asset_tag: data.asset_tag
        ||
        null
            ,
            
        asset_type: data.asset_type
        ||
        null
            ,
            
        purchase_date: data.purchase_date
        ||
        null
            ,
            
        purchase_cost: data.purchase_cost
        ||
        null
            ,
            
        useful_life_months: data.useful_life_months
        ||
        null
            ,
            
        salvage_value: data.salvage_value
        ||
        null
            ,
            
        depreciation_method: data.depreciation_method
        ||
        null
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await assets.setBranch( data.branch || null, {
            transaction,
        });
        
        await assets.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return assets;
    }
    

    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 assetsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                asset_name: item.asset_name
            ||
            null
            ,
            
                asset_tag: item.asset_tag
            ||
            null
            ,
            
                asset_type: item.asset_type
            ||
            null
            ,
            
                purchase_date: item.purchase_date
            ||
            null
            ,
            
                purchase_cost: item.purchase_cost
            ||
            null
            ,
            
                useful_life_months: item.useful_life_months
            ||
            null
            ,
            
                salvage_value: item.salvage_value
            ||
            null
            ,
            
                depreciation_method: item.depreciation_method
            ||
            null
            ,
            
                is_active: item.is_active
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return assets;
    }

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


        

        const updatePayload = {};
        
        if (data.asset_name !== undefined) updatePayload.asset_name = data.asset_name;
        
        
        if (data.asset_tag !== undefined) updatePayload.asset_tag = data.asset_tag;
        
        
        if (data.asset_type !== undefined) updatePayload.asset_type = data.asset_type;
        
        
        if (data.purchase_date !== undefined) updatePayload.purchase_date = data.purchase_date;
        
        
        if (data.purchase_cost !== undefined) updatePayload.purchase_cost = data.purchase_cost;
        
        
        if (data.useful_life_months !== undefined) updatePayload.useful_life_months = data.useful_life_months;
        
        
        if (data.salvage_value !== undefined) updatePayload.salvage_value = data.salvage_value;
        
        
        if (data.depreciation_method !== undefined) updatePayload.depreciation_method = data.depreciation_method;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.branch !== undefined) {
            await assets.setBranch(
              
              data.branch,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await assets.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return assets;
    }

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

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

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


        return assets;
    }

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

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

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

        await assets.destroy({
            transaction
        });

        return assets;
    }

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

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

        if (!assets) {
            return assets;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.branch = await assets.getBranch({
            transaction
        });
        
        
        output.organizations = await assets.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.branches,
        as: 'branch',
        
        where: filter.branch ? {
          [Op.or]: [
            { id: { [Op.in]: filter.branch.split('|').map(term => Utils.uuid(term)) } },
            {
              branch_name: {
                [Op.or]: filter.branch.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.asset_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'assets',
                        'asset_name',
                        filter.asset_name,
                    ),
                };
            }
            
            if (filter.asset_tag) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'assets',
                        'asset_tag',
                        filter.asset_tag,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

            
            if (filter.asset_type) {
                where = {
                    ...where,
                asset_type: filter.asset_type,
            };
            }
            
            if (filter.depreciation_method) {
                where = {
                    ...where,
                depreciation_method: filter.depreciation_method,
            };
            }
            
            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.assets.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(
                        'assets',
                        'asset_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

