"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AttachedFilesService = void 0;
const mongoose_1 = __importDefault(require("mongoose"));
const path_1 = __importDefault(require("path"));
const TransactionAttachedFile_Model_1 = require("../models/TransactionAttachedFile.Model");
class AttachedFilesService {
    saveFilesToAws;
    rootDir;
    s3Read;
    bucketName;
    constructor(deps) {
        this.saveFilesToAws = deps.saveFilesToAws;
        this.rootDir = deps.rootDir;
        this.s3Read = deps.s3Read;
        this.bucketName = deps.bucketName;
    }
    async downloadAttachedFile(fileId) {
        const DBFile = await TransactionAttachedFile_Model_1.TransactionAttachedFileModel.findById(fileId).lean();
        if (!DBFile) {
            return null;
        }
        return DBFile;
    }
    async getEffectiveDateList(borrowerId) {
        const result = await TransactionAttachedFile_Model_1.TransactionAttachedFileModel.aggregate([
            {
                $match: {
                    borrowerId: new mongoose_1.default.Types.ObjectId(borrowerId),
                },
            },
            {
                $group: {
                    _id: null,
                    effectiveDates: { $addToSet: '$effectiveDate' },
                },
            },
            {
                $unwind: '$effectiveDates',
            },
            {
                $sort: { 'effectiveDates': -1 },
            },
            {
                $group: {
                    _id: null,
                    effectiveDates: { $push: '$effectiveDates' },
                },
            },
        ]);
        return result.reduce((acc, item) => [...acc, ...item.effectiveDates], []);
    }
    async getLatestEffectiveDate(borrowerId) {
        const latsEffectiveDateDoc = await TransactionAttachedFile_Model_1.TransactionAttachedFileModel.find({ borrowerId }).sort({ effectiveDate: -1 }).limit(1).lean();
        if (!latsEffectiveDateDoc.length) {
            return null;
        }
        return latsEffectiveDateDoc[0].effectiveDate;
    }
    async getAttachedFilesByEffectiveDate(effectiveDate) {
        return TransactionAttachedFile_Model_1.TransactionAttachedFileModel.find({ effectiveDate }).sort({ originalName: 1 });
    }
    async getAttachedFilesByEffectiveDatAndBorrowerId(effectiveDate, borrowerId) {
        return TransactionAttachedFile_Model_1.TransactionAttachedFileModel.find({ effectiveDate, borrowerId }).sort({ originalName: 1 });
    }
    async createAttachedFile(file, userId, effectiveDate, borrowerId) {
        const newFile = {
            userId,
            filename: file.filename,
            originalName: file.originalName,
            effectiveDate,
            borrowerId: new mongoose_1.default.Types.ObjectId(borrowerId),
        };
        return await TransactionAttachedFile_Model_1.TransactionAttachedFileModel.create(newFile);
    }
    async getAttachedRealFilesByTransactionFileId(borrowerId, effectiveDate) {
        const DBFiles = await TransactionAttachedFile_Model_1.TransactionAttachedFileModel.find({ effectiveDate, borrowerId }).lean();
        if (this.saveFilesToAws) {
            const downloadedFiles = [];
            await Promise.all(DBFiles.map(async (file) => {
                const fileData = await this.s3Read.getObject({
                    Bucket: this.bucketName,
                    Key: file.filename,
                }).promise();
                downloadedFiles.push({
                    filename: file.originalName,
                    content: fileData.Body,
                });
            }));
            return downloadedFiles;
        }
        else {
            return DBFiles.map((file) => ({
                filename: file.originalName,
                path: path_1.default.resolve(this.rootDir, file.filename),
            }));
        }
    }
}
exports.AttachedFilesService = AttachedFilesService;
