
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,
        
        group_code: data.group_code
        ||
        null
            ,
            
        item_code: data.item_code
        ||
        null
            ,
            
        description_text: data.description_text
        ||
        null
            ,
            
        country: data.country
        ||
        null
            ,
            
        registration_number: data.registration_number
        ||
        null
            ,
            
        value_previous_year: data.value_previous_year
        ||
        null
            ,
            
        value_current_year: data.value_current_year
        ||
        null
            ,
            
        disposed_in_year: data.disposed_in_year
        ||
        false
        
            ,
            
        disposal_value: data.disposal_value
        ||
        null
            ,
            
        buyer_document: data.buyer_document
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await assets.setDeclaration( data.declaration || 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,
                
                group_code: item.group_code
            ||
            null
            ,
            
                item_code: item.item_code
            ||
            null
            ,
            
                description_text: item.description_text
            ||
            null
            ,
            
                country: item.country
            ||
            null
            ,
            
                registration_number: item.registration_number
            ||
            null
            ,
            
                value_previous_year: item.value_previous_year
            ||
            null
            ,
            
                value_current_year: item.value_current_year
            ||
            null
            ,
            
                disposed_in_year: item.disposed_in_year
            ||
            false
        
            ,
            
                disposal_value: item.disposal_value
            ||
            null
            ,
            
                buyer_document: item.buyer_document
            ||
            null
            ,
            
            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.group_code !== undefined) updatePayload.group_code = data.group_code;
        
        
        if (data.item_code !== undefined) updatePayload.item_code = data.item_code;
        
        
        if (data.description_text !== undefined) updatePayload.description_text = data.description_text;
        
        
        if (data.country !== undefined) updatePayload.country = data.country;
        
        
        if (data.registration_number !== undefined) updatePayload.registration_number = data.registration_number;
        
        
        if (data.value_previous_year !== undefined) updatePayload.value_previous_year = data.value_previous_year;
        
        
        if (data.value_current_year !== undefined) updatePayload.value_current_year = data.value_current_year;
        
        
        if (data.disposed_in_year !== undefined) updatePayload.disposed_in_year = data.disposed_in_year;
        
        
        if (data.disposal_value !== undefined) updatePayload.disposal_value = data.disposal_value;
        
        
        if (data.buyer_document !== undefined) updatePayload.buyer_document = data.buyer_document;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.declaration !== undefined) {
            await assets.setDeclaration(
              
              data.declaration,
              
              { 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.declaration = await assets.getDeclaration({
            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.declarations,
        as: 'declaration',
        
        where: filter.declaration ? {
          [Op.or]: [
            { id: { [Op.in]: filter.declaration.split('|').map(term => Utils.uuid(term)) } },
            {
              status: {
                [Op.or]: filter.declaration.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.group_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'assets',
                        'group_code',
                        filter.group_code,
                    ),
                };
            }
            
            if (filter.item_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'assets',
                        'item_code',
                        filter.item_code,
                    ),
                };
            }
            
            if (filter.description_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'assets',
                        'description_text',
                        filter.description_text,
                    ),
                };
            }
            
            if (filter.country) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'assets',
                        'country',
                        filter.country,
                    ),
                };
            }
            
            if (filter.registration_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'assets',
                        'registration_number',
                        filter.registration_number,
                    ),
                };
            }
            
            if (filter.buyer_document) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'assets',
                        'buyer_document',
                        filter.buyer_document,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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


      

      
      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',
                        'item_code',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

