"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.LocalProvider = void 0;
const common_1 = require("@nestjs/common");
const fs_1 = require("fs");
const promises_1 = require("fs/promises");
const path = __importStar(require("path"));
const path_1 = require("path");
const abstract_provider_1 = require("./abstract.provider");
class LocalProvider extends abstract_provider_1.AbstractProvider {
    constructor(setting, jwt) {
        super();
        this.setting = setting;
        this.jwt = jwt;
        this.initValidation();
    }
    async initValidation() {
        if (!this.setting['storage-local-path']) {
            throw new common_1.BadRequestException(`You must set the storage-local-path in the setting.`);
        }
        if (!(0, fs_1.existsSync)(this.setting['storage-local-path'])) {
            await this.createFolderRecursive(this.setting['storage-local-path']);
        }
    }
    async createFolderRecursive(path) {
        const folders = (0, path_1.join)(path).split(path_1.sep);
        let currentPath = '';
        for (const folder of folders) {
            currentPath = (0, path_1.join)(currentPath, folder);
            if (!(0, fs_1.existsSync)(currentPath)) {
                await (0, promises_1.mkdir)(currentPath, { recursive: true });
            }
        }
    }
    resolveFilepath(filepath) {
        return path.isAbsolute(filepath) ? filepath : path.resolve(filepath);
    }
    async uploadFromString(destination, filename, fileContent, mimetype) {
        const storagePath = (0, path_1.join)(this.setting['storage-local-path'], destination);
        if (!storagePath) {
            throw new common_1.BadRequestException(`You must set the storage-local-path in the setting.`);
        }
        if (!(0, fs_1.existsSync)(storagePath)) {
            await this.createFolderRecursive(storagePath);
        }
        if (!(0, fs_1.existsSync)(storagePath)) {
            throw new common_1.BadRequestException(`The storage path does not exist: ${storagePath}`);
        }
        const filePath = (0, path_1.join)(storagePath, this.getFilename(filename));
        await (0, promises_1.writeFile)(filePath, fileContent);
        return filePath;
    }
    async upload(destination, file) {
        const storagePath = (0, path_1.join)(this.setting['storage-local-path'], destination);
        if (!storagePath) {
            throw new common_1.BadRequestException(`You must set the storage-local-path in the setting.`);
        }
        if (!(0, fs_1.existsSync)(storagePath)) {
            await this.createFolderRecursive(storagePath);
        }
        if (!(0, fs_1.existsSync)(storagePath)) {
            throw new common_1.BadRequestException(`The storage path does not exist: ${storagePath}`);
        }
        const filePath = (0, path_1.join)(storagePath, this.getFilename(file.originalname));
        await (0, promises_1.writeFile)(filePath, file.buffer);
        return filePath;
    }
    async uploadFromPath(destination, filePath, options) {
        var _a;
        const sourcePath = this.resolveFilepath(filePath);
        if (!(0, fs_1.existsSync)(sourcePath)) {
            throw new common_1.BadRequestException(`File not found: ${sourcePath}`);
        }
        const sourceStats = await (0, promises_1.stat)(sourcePath);
        if (!sourceStats.isFile()) {
            throw new common_1.BadRequestException(`Invalid file path: ${sourcePath}`);
        }
        const storagePath = (0, path_1.join)(this.setting['storage-local-path'], destination);
        if (!(0, fs_1.existsSync)(storagePath)) {
            await this.createFolderRecursive(storagePath);
        }
        const targetFilename = this.getFilename((_a = options === null || options === void 0 ? void 0 : options.filename) !== null && _a !== void 0 ? _a : (0, path_1.basename)(sourcePath));
        const targetPath = (0, path_1.join)(storagePath, targetFilename);
        await (0, promises_1.copyFile)(sourcePath, targetPath);
        return targetPath;
    }
    async delete(filepath) {
        const fullPath = this.resolveFilepath(filepath);
        if (!(0, fs_1.existsSync)(fullPath)) {
            throw new common_1.BadRequestException(`File not found: ${fullPath}`);
        }
        return (0, promises_1.unlink)(fullPath);
    }
    async readStream(filepath) {
        const fullPath = this.resolveFilepath(filepath);
        if (!(0, fs_1.existsSync)(fullPath)) {
            throw new common_1.BadRequestException(`File not found: ${fullPath}`);
        }
        return (0, fs_1.createReadStream)(fullPath);
    }
    async metaData(filepath) {
        const fullPath = this.resolveFilepath(filepath);
        if (!(0, fs_1.existsSync)(fullPath)) {
            throw new common_1.BadRequestException(`File not found: ${fullPath}`);
        }
        return {
            size: (await this.buffer(fullPath)).length,
        };
    }
    async buffer(filepath) {
        const fullPath = this.resolveFilepath(filepath);
        if (!(0, fs_1.existsSync)(fullPath)) {
            throw new common_1.BadRequestException(`File not found: ${fullPath}`);
        }
        return fs_1.promises.readFile(fullPath);
    }
    async tempURL(filepath, expires = 3600) {
        try {
            const token = this.jwt.sign({ filepath }, {
                secret: process.env.JWT_SECRET,
                expiresIn: expires,
            });
            const host = process.env.HOST || 'localhost';
            const port = process.env.PORT || 3100;
            return `http://${host}:${port}/file/download/${token}`;
        }
        catch (error) {
            throw new common_1.BadRequestException(error);
        }
    }
}
exports.LocalProvider = LocalProvider;
//# sourceMappingURL=local.provider.js.map