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

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

        const case_documents = await db.case_documents.create(
            {
                id: data.id || undefined,
        
        document_type: data.document_type
        ||
        null
            ,
            
        source_channel: data.source_channel
        ||
        null
            ,
            
        storage_key: data.storage_key
        ||
        null
            ,
            
        original_filename: data.original_filename
        ||
        null
            ,
            
        checksum: data.checksum
        ||
        null
            ,
            
        uploaded_at: data.uploaded_at
        ||
        null
            ,
            
        version_number: data.version_number
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await case_documents.setAuthorization_case( data.authorization_case || null, {
            transaction,
        });
        
        await case_documents.setUploaded_by_user( data.uploaded_by_user || null, {
            transaction,
        });
        
        await case_documents.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return case_documents;
    }
    

    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 case_documentsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                document_type: item.document_type
            ||
            null
            ,
            
                source_channel: item.source_channel
            ||
            null
            ,
            
                storage_key: item.storage_key
            ||
            null
            ,
            
                original_filename: item.original_filename
            ||
            null
            ,
            
                checksum: item.checksum
            ||
            null
            ,
            
                uploaded_at: item.uploaded_at
            ||
            null
            ,
            
                version_number: item.version_number
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return case_documents;
    }

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


        

        const updatePayload = {};
        
        if (data.document_type !== undefined) updatePayload.document_type = data.document_type;
        
        
        if (data.source_channel !== undefined) updatePayload.source_channel = data.source_channel;
        
        
        if (data.storage_key !== undefined) updatePayload.storage_key = data.storage_key;
        
        
        if (data.original_filename !== undefined) updatePayload.original_filename = data.original_filename;
        
        
        if (data.checksum !== undefined) updatePayload.checksum = data.checksum;
        
        
        if (data.uploaded_at !== undefined) updatePayload.uploaded_at = data.uploaded_at;
        
        
        if (data.version_number !== undefined) updatePayload.version_number = data.version_number;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.authorization_case !== undefined) {
            await case_documents.setAuthorization_case(
              
              data.authorization_case,
              
              { transaction }
            );
        }
        
        if (data.uploaded_by_user !== undefined) {
            await case_documents.setUploaded_by_user(
              
              data.uploaded_by_user,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await case_documents.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return case_documents;
    }

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

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

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


        return case_documents;
    }

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

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

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

        await case_documents.destroy({
            transaction
        });

        return case_documents;
    }

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

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

        if (!case_documents) {
            return case_documents;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.ai_jobs_case_document = await case_documents.getAi_jobs_case_document({
            transaction
        });
        
        
        
        
        
        
        
        
        output.authorization_case = await case_documents.getAuthorization_case({
            transaction
        });
        
        
        output.uploaded_by_user = await case_documents.getUploaded_by_user({
            transaction
        });
        
        
        output.organizations = await case_documents.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.authorization_cases,
        as: 'authorization_case',
        
        where: filter.authorization_case ? {
          [Op.or]: [
            { id: { [Op.in]: filter.authorization_case.split('|').map(term => Utils.uuid(term)) } },
            {
              site_of_service: {
                [Op.or]: filter.authorization_case.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.users,
        as: 'uploaded_by_user',
        
        where: filter.uploaded_by_user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.uploaded_by_user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.uploaded_by_user.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.storage_key) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'case_documents',
                        'storage_key',
                        filter.storage_key,
                    ),
                };
            }
            
            if (filter.original_filename) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'case_documents',
                        'original_filename',
                        filter.original_filename,
                    ),
                };
            }
            
            if (filter.checksum) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'case_documents',
                        'checksum',
                        filter.checksum,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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


      

      

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

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

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

    
};

