"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.PostsService = void 0;
const common_1 = require("@nestjs/common");
const typeorm_1 = require("@nestjs/typeorm");
const typeorm_2 = require("typeorm");
const post_entity_1 = require("./post.entity");
const likes_entity_1 = require("./likes.entity");
const comments_entity_1 = require("./comments.entity");
let PostsService = class PostsService {
    constructor(postRepo, likeRepo, commentRepo) {
        this.postRepo = postRepo;
        this.likeRepo = likeRepo;
        this.commentRepo = commentRepo;
    }
    findAll() {
        return this.postRepo.find({
            order: { createdAt: 'DESC' },
            relations: ['author', 'likes', 'comments', 'comments.author'],
        });
    }
    async getFeed(userId, followedUserIds) {
        const query = this.postRepo.createQueryBuilder('post')
            .leftJoinAndSelect('post.author', 'author')
            .leftJoinAndSelect('post.likes', 'likes')
            .leftJoinAndSelect('post.comments', 'comments')
            .leftJoinAndSelect('comments.author', 'commentAuthor')
            .orderBy('post.createdAt', 'DESC');
        if (followedUserIds && followedUserIds.length > 0) {
            query.where('author.id IN (:...userIds)', { userIds: [userId, ...followedUserIds] });
        }
        return query.getMany();
    }
    async findOne(id) {
        const post = await this.postRepo.findOne({
            where: { id },
            relations: ['author', 'likes', 'comments', 'comments.author'],
        });
        if (!post)
            throw new common_1.NotFoundException('Post not found');
        return post;
    }
    create(data) {
        const entity = this.postRepo.create(data);
        return this.postRepo.save(entity);
    }
    async createWithImage(data, imageUrl) {
        const postData = { ...data, imageUrl };
        const entity = this.postRepo.create(postData);
        const savedPost = await this.postRepo.save(entity);
        return this.postRepo.findOne({
            where: { id: savedPost.id },
            relations: ['author', 'likes', 'comments'],
        });
    }
    async verifyPostOwnership(postId, userId) {
        const post = await this.findOne(postId);
        if (!post)
            throw new common_1.NotFoundException('Post not found');
        if (post.author.id !== userId) {
            throw new common_1.ForbiddenException('You can only edit your own posts');
        }
        return post;
    }
    async update(id, data, userId) {
        const post = await this.findOne(id);
        if (!post)
            throw new common_1.NotFoundException('Post not found');
        if (userId && post.author.id !== userId) {
            throw new common_1.ForbiddenException('You can only edit your own posts');
        }
        Object.assign(post, data);
        return this.postRepo.save(post);
    }
    remove(id) {
        return this.postRepo.delete(id);
    }
    async getLikesByPost(postId) {
        return this.likeRepo.find({
            where: { post: { id: postId } },
            relations: ['user', 'post'],
        });
    }
    async addLike(postId, userId) {
        const post = await this.findOne(postId);
        if (!post)
            throw new common_1.NotFoundException('Post not found');
        const existing = await this.likeRepo.findOne({
            where: { post: { id: postId }, user: { id: userId } },
        });
        if (existing)
            return existing;
        const like = this.likeRepo.create({
            post,
            user: { id: userId },
        });
        await this.likeRepo.save(like);
        return { message: 'Post liked', likeId: like.id };
    }
    async removeLike(postId, userId) {
        const existing = await this.likeRepo.findOne({
            where: { post: { id: postId }, user: { id: userId } },
        });
        if (!existing)
            throw new common_1.NotFoundException('Like not found');
        await this.likeRepo.delete(existing.id);
        return { message: 'Post unliked' };
    }
    async addComment(postId, userId, content) {
        const post = await this.findOne(postId);
        if (!post)
            throw new common_1.NotFoundException('Post not found');
        const comment = this.commentRepo.create({
            post,
            author: { id: userId },
            content,
        });
        await this.commentRepo.save(comment);
        return comment;
    }
    async updateComment(commentId, userId, content) {
        const comment = await this.commentRepo.findOne({
            where: { id: commentId },
            relations: ['author'],
        });
        if (!comment)
            throw new common_1.NotFoundException('Comment not found');
        if (comment.author.id !== userId)
            throw new common_1.ForbiddenException('Not your comment');
        comment.content = content;
        await this.commentRepo.save(comment);
        return { message: 'Comment updated', comment };
    }
    async deleteComment(commentId, userId) {
        const comment = await this.commentRepo.findOne({
            where: { id: commentId },
            relations: ['author'],
        });
        if (!comment)
            throw new common_1.NotFoundException('Comment not found');
        if (comment.author.id !== userId)
            throw new common_1.ForbiddenException('Not your comment');
        await this.commentRepo.delete(comment.id);
        return { message: 'Comment deleted' };
    }
    async getCommentsByPost(postId) {
        return this.commentRepo.find({
            where: { post: { id: postId } },
            relations: ['author', 'post'],
            order: { createdAt: 'DESC' },
        });
    }
};
exports.PostsService = PostsService;
exports.PostsService = PostsService = __decorate([
    (0, common_1.Injectable)(),
    __param(0, (0, typeorm_1.InjectRepository)(post_entity_1.PostEntity)),
    __param(1, (0, typeorm_1.InjectRepository)(likes_entity_1.LikesEntity)),
    __param(2, (0, typeorm_1.InjectRepository)(comments_entity_1.CommentsEntity)),
    __metadata("design:paramtypes", [typeorm_2.Repository,
        typeorm_2.Repository,
        typeorm_2.Repository])
], PostsService);
//# sourceMappingURL=posts.service.js.map