"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 __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
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.UploadService = void 0;
const common_1 = require("@nestjs/common");
const fs = __importStar(require("fs"));
const path_1 = require("path");
let UploadService = class UploadService {
    async saveImage(file, folderName = 'temp') {
        if (!file) {
            throw new common_1.HttpException('File not uploaded', common_1.HttpStatus.BAD_REQUEST);
        }
        const uploadDir = `uploads/${folderName}`;
        if (!fs.existsSync(uploadDir)) {
            fs.mkdirSync(uploadDir, { recursive: true });
        }
        const timestamp = Date.now();
        const originalName = file.originalname.split('.')[0];
        const extension = (0, path_1.extname)(file.originalname);
        const uniqueFilename = `${originalName}_${timestamp}${extension}`;
        const filePath = `${uploadDir}/${uniqueFilename}`;
        await fs.promises.writeFile(filePath, file.buffer);
        const fileData = {
            file_name: filePath,
            original_name: file.originalname,
            file_size: file.size,
            mime_type: file.mimetype,
        };
        return fileData;
    }
    async saveImages(files, folderName = 'common') {
        if (!files) {
            throw new common_1.HttpException('Files not uploaded', common_1.HttpStatus.BAD_REQUEST);
        }
        const uploadDir = `uploads/${folderName}`;
        if (!fs.existsSync(uploadDir)) {
            fs.mkdirSync(uploadDir, { recursive: true });
        }
        const fileNames = [];
        for (const file of files) {
            const fileData = await this.saveImage(file, folderName);
            fileNames.push(fileData);
        }
        return fileNames;
    }
    async removeImage(fileData) {
        if (!fs.existsSync(fileData?.file_name)) {
            return;
        }
        await fs.promises.unlink(fileData?.file_name);
    }
    async removeImages(fileDataArray) {
        for (const fileData of fileDataArray) {
            await this.removeImage(fileData);
        }
    }
    async moveImage(oldData, movedFolderName) {
        const movedFolder = `uploads/${movedFolderName}`;
        if (!fs.existsSync(movedFolder)) {
            fs.mkdirSync(movedFolder, { recursive: true });
        }
        const host = process.env.SERVER_HOST || 'http://localhost:8000';
        const timestamp = Date.now();
        const filePath = oldData.file_name.replace(`${host}/`, '');
        const extension = (0, path_1.extname)(filePath);
        const originalName = oldData.original_name.split('.')[0];
        const uniqueFilename = `${originalName}_${timestamp}${extension}`;
        const newPath = `${movedFolder}/${uniqueFilename}`;
        await fs.promises.copyFile(filePath, newPath);
        return {
            ...oldData,
            file_name: newPath,
        };
    }
    async moveImages(oldDataList, movedFolderName) {
        const movedFolder = `uploads/${movedFolderName}`;
        if (!fs.existsSync(movedFolder)) {
            fs.mkdirSync(movedFolder, { recursive: true });
        }
        const newDataList = [];
        for (const oldData of oldDataList) {
            const newData = await this.moveImage(oldData, movedFolderName);
            newDataList.push(newData);
        }
        this.removeOldTempFiles();
        return newDataList;
    }
    async removeOldTempFile(filePath) {
        await fs.promises.unlink(filePath);
    }
    async removeOldTempFiles(tempFolderName = 'temp') {
        const tempFolder = `uploads/${tempFolderName}`;
        if (!fs.existsSync(tempFolder)) {
            return;
        }
        const files = await fs.promises.readdir(tempFolder);
        const now = Date.now();
        for (const file of files) {
            const filePath = `${tempFolder}/${file}`;
            const stats = await fs.promises.stat(filePath);
            const fileAge = now - stats.birthtimeMs;
            if (fileAge > 24 * 60 * 60 * 1000) {
                await fs.promises.unlink(filePath);
            }
        }
    }
};
exports.UploadService = UploadService;
exports.UploadService = UploadService = __decorate([
    (0, common_1.Injectable)()
], UploadService);
//# sourceMappingURL=upload.service.js.map