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

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

        const files = await db.files.create(
            {
                id: data.id || undefined,
        
        file_name: data.file_name
        ||
        null
            ,
            
        content_type: data.content_type
        ||
        null
            ,
            
        file_extension: data.file_extension
        ||
        null
            ,
            
        size_bytes: data.size_bytes
        ||
        null
            ,
            
        storage_provider: data.storage_provider
        ||
        null
            ,
            
        storage_key: data.storage_key
        ||
        null
            ,
            
        checksum_sha256: data.checksum_sha256
        ||
        null
            ,
            
        is_ocr_required: data.is_ocr_required
        ||
        false
        
            ,
            
        processing_status: data.processing_status
        ||
        null
            ,
            
        uploaded_at: data.uploaded_at
        ||
        null
            ,
            
        tags: data.tags
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await files.setOwner( data.owner || null, {
            transaction,
        });
        
        await files.setMatter( data.matter || null, {
            transaction,
        });
        

        

        

        return files;
    }
    

    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 filesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                file_name: item.file_name
            ||
            null
            ,
            
                content_type: item.content_type
            ||
            null
            ,
            
                file_extension: item.file_extension
            ||
            null
            ,
            
                size_bytes: item.size_bytes
            ||
            null
            ,
            
                storage_provider: item.storage_provider
            ||
            null
            ,
            
                storage_key: item.storage_key
            ||
            null
            ,
            
                checksum_sha256: item.checksum_sha256
            ||
            null
            ,
            
                is_ocr_required: item.is_ocr_required
            ||
            false
        
            ,
            
                processing_status: item.processing_status
            ||
            null
            ,
            
                uploaded_at: item.uploaded_at
            ||
            null
            ,
            
                tags: item.tags
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return files;
    }

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

        const files = await db.files.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.file_name !== undefined) updatePayload.file_name = data.file_name;
        
        
        if (data.content_type !== undefined) updatePayload.content_type = data.content_type;
        
        
        if (data.file_extension !== undefined) updatePayload.file_extension = data.file_extension;
        
        
        if (data.size_bytes !== undefined) updatePayload.size_bytes = data.size_bytes;
        
        
        if (data.storage_provider !== undefined) updatePayload.storage_provider = data.storage_provider;
        
        
        if (data.storage_key !== undefined) updatePayload.storage_key = data.storage_key;
        
        
        if (data.checksum_sha256 !== undefined) updatePayload.checksum_sha256 = data.checksum_sha256;
        
        
        if (data.is_ocr_required !== undefined) updatePayload.is_ocr_required = data.is_ocr_required;
        
        
        if (data.processing_status !== undefined) updatePayload.processing_status = data.processing_status;
        
        
        if (data.uploaded_at !== undefined) updatePayload.uploaded_at = data.uploaded_at;
        
        
        if (data.tags !== undefined) updatePayload.tags = data.tags;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.owner !== undefined) {
            await files.setOwner(
              
              data.owner,
              
              { transaction }
            );
        }
        
        if (data.matter !== undefined) {
            await files.setMatter(
              
              data.matter,
              
              { transaction }
            );
        }
        

        
        

        

        return files;
    }

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

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

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


        return files;
    }

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

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

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

        await files.destroy({
            transaction
        });

        return files;
    }

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

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

        if (!files) {
            return files;
        }

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

        
        
        
        
        
        
        
        
        
        output.file_extractions_file = await files.getFile_extractions_file({
            transaction
        });
        
        
        
        
        output.ai_jobs_file = await files.getAi_jobs_file({
            transaction
        });
        
        
        output.legal_templates_source_file = await files.getLegal_templates_source_file({
            transaction
        });
        
        
        
        output.generated_documents_export_file = await files.getGenerated_documents_export_file({
            transaction
        });
        
        
        
        
        
        
        
        
        
        output.mock_trial_turns_audio_file = await files.getMock_trial_turns_audio_file({
            transaction
        });
        
        
        output.transcription_jobs_media_file = await files.getTranscription_jobs_media_file({
            transaction
        });
        
        output.transcription_jobs_export_file = await files.getTranscription_jobs_export_file({
            transaction
        });
        
        
        output.medical_chronology_reports_export_file = await files.getMedical_chronology_reports_export_file({
            transaction
        });
        
        
        output.medical_events_linked_file = await files.getMedical_events_linked_file({
            transaction
        });
        
        
        output.causation_analyses_export_file = await files.getCausation_analyses_export_file({
            transaction
        });
        
        
        
        
        output.owner = await files.getOwner({
            transaction
        });
        
        
        output.matter = await files.getMatter({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        

        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

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

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



    ];

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

            
            if (filter.file_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'files',
                        'file_name',
                        filter.file_name,
                    ),
                };
            }
            
            if (filter.content_type) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'files',
                        'content_type',
                        filter.content_type,
                    ),
                };
            }
            
            if (filter.file_extension) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'files',
                        'file_extension',
                        filter.file_extension,
                    ),
                };
            }
            
            if (filter.storage_provider) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'files',
                        'storage_provider',
                        filter.storage_provider,
                    ),
                };
            }
            
            if (filter.storage_key) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'files',
                        'storage_key',
                        filter.storage_key,
                    ),
                };
            }
            
            if (filter.checksum_sha256) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'files',
                        'checksum_sha256',
                        filter.checksum_sha256,
                    ),
                };
            }
            
            if (filter.tags) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'files',
                        'tags',
                        filter.tags,
                    ),
                };
            }
            

            
            

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    size_bytes: {
                    ...where.size_bytes,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            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.active !== undefined) {
                where = {
                    ...where,
                    active: filter.active === true || filter.active === 'true'
                };
            }

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


      

      



            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,
                        },
                    };
                }
            }
        }
        

        

        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.files.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, ) {
        let where = {};
        
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'files',
                        'file_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

