"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.FileManagerService = void 0;
const mongoose_1 = __importDefault(require("mongoose"));
const BorrowerCompliance_model_1 = require("../models/BorrowerCompliance.model");
class FileManagerService {
    getComplianceBorrowersService;
    constructor(getComplianceBorrowersService) {
        this.getComplianceBorrowersService = getComplianceBorrowersService;
    }
    async getAwsFileId(borrowerId, instanceId, fileId) {
        try {
            const borrower = await BorrowerCompliance_model_1.BorrowerCompliance
                .findOne({ '_id': borrowerId, 'items.instances._id': instanceId, 'items.instances.files._id': fileId })
                .select('+items.instances.files.fileId');
            if (borrower) {
                const files = borrower.items.reduce((acc, item) => {
                    return [...acc, ...item.instances.reduce((accI, instance) => {
                            return [...accI, ...instance.files];
                        }, [])];
                }, []);
                const foundFile = files.find((file) => file._id.toString() === fileId);
                return foundFile.fileId;
            }
            return null;
        }
        catch (e) {
            console.error(e);
            return null;
        }
    }
    async uploadFile(complianceBorrowerId, instanceId, originalName, uuid, user) {
        try {
            const items = await this.findItemByInstanceId(instanceId);
            if (items.length > 0) {
                const itemId = items.pop().items._id;
                await BorrowerCompliance_model_1.BorrowerCompliance
                    .findOneAndUpdate({ _id: complianceBorrowerId }, {
                    $set: {
                        'items.$[item].instances.$[instance].submittedDate': (new Date()).toISOString(),
                        'items.$[item].instances.$[instance].status': 'IN_REVIEW',
                    },
                    $push: {
                        'items.$[item].instances.$[instance].files': {
                            'fileId': uuid,
                            'name': originalName,
                            'isNew': true,
                            'uploadedAt': new Date(),
                            'uploadedBy': user?._id,
                        },
                    },
                }, {
                    arrayFilters: [
                        { 'item._id': itemId },
                        { 'instance._id': new mongoose_1.default.Types.ObjectId(instanceId) },
                    ],
                });
            }
        }
        catch (e) {
            console.error(e);
        }
    }
    async findItemByInstanceId(instanceId) {
        return BorrowerCompliance_model_1.BorrowerCompliance.aggregate([
            { $unwind: '$items' },
            { $unwind: '$items.instances' },
            { $match: { 'items.instances._id': new mongoose_1.default.Types.ObjectId(instanceId) } },
        ]);
    }
    async getFilesNewerThanDate(date) {
        const borrowerWithFiles = await BorrowerCompliance_model_1.BorrowerCompliance.aggregate([
            { $unwind: '$items' },
            { $unwind: '$items.instances' },
            { $unwind: '$items.instances.files' },
            { $match: { 'items.instances.files.uploadedAt': { $gte: new Date(date) } } },
            {
                $group: {
                    _id: '$_id',
                    borrower: { $first: '$borrower' },
                    files: { $addToSet: '$items.instances.files' },
                },
            },
        ]);
        return await BorrowerCompliance_model_1.BorrowerCompliance.populate(borrowerWithFiles, { path: 'borrower' });
    }
    async deleteFile(complianceBorrowerId, fileId) {
        try {
            await BorrowerCompliance_model_1.BorrowerCompliance
                .findOneAndUpdate({ _id: complianceBorrowerId }, { '$pull': { 'items.$[].instances.$[].files': { _id: fileId } } });
        }
        catch (e) {
            console.error(e);
        }
    }
    async getFilesByBorrowerId(borrowerId) {
        const foundComplianceBorrower = await BorrowerCompliance_model_1.BorrowerCompliance
            .findOne({ borrower: borrowerId })
            .select('+items.instances.files.fileId');
        return foundComplianceBorrower ? foundComplianceBorrower.items : [];
    }
    async updateAWSID(itemId, instanceId, fileId, awsFileId) {
        const complianceBorrowersService = this.getComplianceBorrowersService();
        const complianceBorrower = await complianceBorrowersService.getBorrowerByInstanceId(instanceId);
        await BorrowerCompliance_model_1.BorrowerCompliance
            .findOneAndUpdate({ _id: complianceBorrower._id }, {
            $set: { 'items.$[item].instances.$[instance].files.$[file].fileId': awsFileId },
        }, {
            arrayFilters: [
                { 'item.item': itemId },
                { 'instance._id': new mongoose_1.default.Types.ObjectId(instanceId) },
                { 'file._id': new mongoose_1.default.Types.ObjectId(fileId) },
            ],
        });
    }
}
exports.FileManagerService = FileManagerService;
