"use strict";
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 __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.PostsController = void 0;
exports.storageFactory = storageFactory;
const common_1 = require("@nestjs/common");
const jwt_auth_guard_1 = require("../auth/jwt-auth.guard");
const posts_service_1 = require("./posts.service");
const platform_express_1 = require("@nestjs/platform-express");
const multer_1 = require("multer");
const path_1 = require("path");
const fs = require("fs");
function storageFactory(folder) {
    const uploadPath = (0, path_1.join)(process.cwd(), "uploads", folder);
    if (!fs.existsSync(uploadPath))
        fs.mkdirSync(uploadPath, { recursive: true });
    return (0, multer_1.diskStorage)({
        destination: uploadPath,
        filename: (_req, file, cb) => {
            const uniqueSuffix = `${Date.now()}-${Math.round(Math.random() * 1e9)}`;
            const ext = (0, path_1.extname)(file.originalname);
            const filename = `${uniqueSuffix}${ext}`;
            cb(null, filename);
        },
    });
}
let PostsController = class PostsController {
    constructor(postsService) {
        this.postsService = postsService;
    }
    list() {
        return this.postsService.findAll();
    }
    get(id) {
        return this.postsService.findOne(id);
    }
    async create(body, image, req) {
        let imageUrl;
        if (image) {
            const savedFilename = image.filename || image.originalname;
            const savedPath = (0, path_1.join)(process.cwd(), "uploads", "posts", savedFilename);
            if (fs.existsSync(savedPath))
                imageUrl = `/uploads/posts/${savedFilename}`;
        }
        const authorId = req.user.userId;
        const postData = {
            content: body.content,
            author: { id: authorId },
        };
        const post = await this.postsService.createWithImage(postData, imageUrl);
        if (!post) {
            throw new Error('Failed to create post');
        }
        return {
            id: post.id,
            content: post.content,
            imageUrl: post.imageUrl,
            createdAt: post.createdAt,
            updatedAt: post.updatedAt,
            author: post.author,
        };
    }
    async update(id, body, image, req) {
        await this.postsService.verifyPostOwnership(id, req.user.userId);
        let imageUrl;
        if (image) {
            const savedFilename = image.filename || image.originalname;
            const savedPath = (0, path_1.join)(process.cwd(), "uploads", "posts", savedFilename);
            if (fs.existsSync(savedPath))
                imageUrl = `/uploads/posts/${savedFilename}`;
        }
        const updateData = {
            content: body.content,
        };
        if (imageUrl) {
            updateData.imageUrl = imageUrl;
        }
        else if (body.removeImage === 'true' || body.removeImage === true) {
            updateData.imageUrl = null;
        }
        const updatedPost = await this.postsService.update(id, updateData, req.user.userId);
        return this.postsService.findOne(id);
    }
    remove(id) {
        return this.postsService.remove(id);
    }
    async getLikes(postId) {
        return this.postsService.getLikesByPost(postId);
    }
    async likePost(postId, req) {
        return this.postsService.addLike(postId, req.user.userId);
    }
    async unlikePost(postId, req) {
        return this.postsService.removeLike(postId, req.user.userId);
    }
    async addComment(postId, body, req) {
        const user = req.user;
        return this.postsService.addComment(postId, user.id, body.content);
    }
    async updateComment(commentId, body, req) {
        const user = req.user;
        return this.postsService.updateComment(commentId, user.id, body.content);
    }
    async deleteComment(commentId, req) {
        const user = req.user;
        return this.postsService.deleteComment(commentId, user.id);
    }
    async getComments(postId) {
        return this.postsService.getCommentsByPost(postId);
    }
};
exports.PostsController = PostsController;
__decorate([
    (0, common_1.Get)(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", []),
    __metadata("design:returntype", void 0)
], PostsController.prototype, "list", null);
__decorate([
    (0, common_1.Get)(":id"),
    __param(0, (0, common_1.Param)("id")),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String]),
    __metadata("design:returntype", void 0)
], PostsController.prototype, "get", null);
__decorate([
    (0, common_1.Post)(),
    (0, common_1.UseInterceptors)((0, platform_express_1.FileInterceptor)("image", {
        storage: storageFactory("posts"),
    })),
    __param(0, (0, common_1.Body)()),
    __param(1, (0, common_1.UploadedFile)()),
    __param(2, (0, common_1.Req)()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, Object, Object]),
    __metadata("design:returntype", Promise)
], PostsController.prototype, "create", null);
__decorate([
    (0, common_1.Patch)(":id"),
    (0, common_1.UseInterceptors)((0, platform_express_1.FileInterceptor)("image", {
        storage: storageFactory("posts"),
    })),
    __param(0, (0, common_1.Param)("id")),
    __param(1, (0, common_1.Body)()),
    __param(2, (0, common_1.UploadedFile)()),
    __param(3, (0, common_1.Req)()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, Object, Object, Object]),
    __metadata("design:returntype", Promise)
], PostsController.prototype, "update", null);
__decorate([
    (0, common_1.Delete)(":id"),
    __param(0, (0, common_1.Param)("id")),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String]),
    __metadata("design:returntype", void 0)
], PostsController.prototype, "remove", null);
__decorate([
    (0, common_1.Get)(":id/likes"),
    __param(0, (0, common_1.Param)("id")),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String]),
    __metadata("design:returntype", Promise)
], PostsController.prototype, "getLikes", null);
__decorate([
    (0, common_1.Post)(":id/like"),
    __param(0, (0, common_1.Param)("id")),
    __param(1, (0, common_1.Req)()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, Object]),
    __metadata("design:returntype", Promise)
], PostsController.prototype, "likePost", null);
__decorate([
    (0, common_1.Delete)(":id/unlike"),
    __param(0, (0, common_1.Param)("id")),
    __param(1, (0, common_1.Req)()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, Object]),
    __metadata("design:returntype", Promise)
], PostsController.prototype, "unlikePost", null);
__decorate([
    (0, common_1.Post)(":id/comments"),
    __param(0, (0, common_1.Param)("id")),
    __param(1, (0, common_1.Body)()),
    __param(2, (0, common_1.Req)()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, Object, Object]),
    __metadata("design:returntype", Promise)
], PostsController.prototype, "addComment", null);
__decorate([
    (0, common_1.Patch)("comments/:commentId"),
    __param(0, (0, common_1.Param)("commentId")),
    __param(1, (0, common_1.Body)()),
    __param(2, (0, common_1.Req)()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, Object, Object]),
    __metadata("design:returntype", Promise)
], PostsController.prototype, "updateComment", null);
__decorate([
    (0, common_1.Delete)("comments/:commentId"),
    __param(0, (0, common_1.Param)("commentId")),
    __param(1, (0, common_1.Req)()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, Object]),
    __metadata("design:returntype", Promise)
], PostsController.prototype, "deleteComment", null);
__decorate([
    (0, common_1.Get)(":id/comments"),
    __param(0, (0, common_1.Param)("id")),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String]),
    __metadata("design:returntype", Promise)
], PostsController.prototype, "getComments", null);
exports.PostsController = PostsController = __decorate([
    (0, common_1.Controller)("posts"),
    (0, common_1.UseGuards)(jwt_auth_guard_1.JwtAuthGuard),
    __metadata("design:paramtypes", [posts_service_1.PostsService])
], PostsController);
//# sourceMappingURL=posts.controller.js.map