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

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

        const archive_items = await db.archive_items.create(
            {
                id: data.id || undefined,
        
        resource_type: data.resource_type
        ||
        null
            ,
            
        resource_reference: data.resource_reference
        ||
        null
            ,
            
        visibility_scope: data.visibility_scope
        ||
        null
            ,
            
        title: data.title
        ||
        null
            ,
            
        keywords: data.keywords
        ||
        null
            ,
            
        amount_usd: data.amount_usd
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        archived_at: data.archived_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await archive_items.setTenant( data.tenant || null, {
            transaction,
        });
        
        await archive_items.setArchived_by( data.archived_by || null, {
            transaction,
        });
        
        await archive_items.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.archive_items.getTableName(),
                belongsToColumn: 'files',
                belongsToId: archive_items.id,
            },
            data.files,
            options,
        );
        

        return archive_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 archive_itemsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                resource_type: item.resource_type
            ||
            null
            ,
            
                resource_reference: item.resource_reference
            ||
            null
            ,
            
                visibility_scope: item.visibility_scope
            ||
            null
            ,
            
                title: item.title
            ||
            null
            ,
            
                keywords: item.keywords
            ||
            null
            ,
            
                amount_usd: item.amount_usd
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                archived_at: item.archived_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        
        for (let i = 0; i < archive_items.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.archive_items.getTableName(),
                    belongsToColumn: 'files',
                    belongsToId: archive_items[i].id,
                },
                data[i].files,
                options,
            );
        }
        

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


        

        const updatePayload = {};
        
        if (data.resource_type !== undefined) updatePayload.resource_type = data.resource_type;
        
        
        if (data.resource_reference !== undefined) updatePayload.resource_reference = data.resource_reference;
        
        
        if (data.visibility_scope !== undefined) updatePayload.visibility_scope = data.visibility_scope;
        
        
        if (data.title !== undefined) updatePayload.title = data.title;
        
        
        if (data.keywords !== undefined) updatePayload.keywords = data.keywords;
        
        
        if (data.amount_usd !== undefined) updatePayload.amount_usd = data.amount_usd;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.archived_at !== undefined) updatePayload.archived_at = data.archived_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.tenant !== undefined) {
            await archive_items.setTenant(
              
              data.tenant,
              
              { transaction }
            );
        }
        
        if (data.archived_by !== undefined) {
            await archive_items.setArchived_by(
              
              data.archived_by,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await archive_items.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.archive_items.getTableName(),
                belongsToColumn: 'files',
                belongsToId: archive_items.id,
            },
            data.files,
            options,
        );
        

        return archive_items;
    }

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

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

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


        return archive_items;
    }

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

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

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

        await archive_items.destroy({
            transaction
        });

        return archive_items;
    }

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

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

        if (!archive_items) {
            return archive_items;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.tenant = await archive_items.getTenant({
            transaction
        });
        
        
        output.archived_by = await archive_items.getArchived_by({
            transaction
        });
        
        
        output.files = await archive_items.getFiles({
            transaction
        });
        
        
        output.organizations = await archive_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.tenants,
        as: 'tenant',
        
        where: filter.tenant ? {
          [Op.or]: [
            { id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.users,
        as: 'archived_by',
        
        where: filter.archived_by ? {
          [Op.or]: [
            { id: { [Op.in]: filter.archived_by.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.archived_by.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.organizations,
        as: 'organizations',
        
      },



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

    ];

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

            
            if (filter.resource_reference) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'archive_items',
                        'resource_reference',
                        filter.resource_reference,
                    ),
                };
            }
            
            if (filter.title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'archive_items',
                        'title',
                        filter.title,
                    ),
                };
            }
            
            if (filter.keywords) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'archive_items',
                        'keywords',
                        filter.keywords,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

            
            if (filter.resource_type) {
                where = {
                    ...where,
                resource_type: filter.resource_type,
            };
            }
            
            if (filter.visibility_scope) {
                where = {
                    ...where,
                visibility_scope: filter.visibility_scope,
            };
            }
            
            if (filter.status) {
                where = {
                    ...where,
                status: filter.status,
            };
            }
            


      

      

      
      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.archive_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(
                        'archive_items',
                        'title',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

