import { Injectable, Logger, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { BlogComment } from 'modules/blog/comments/entities/comment.entity';

import { Blog } from 'modules/blog/entities/blog.entity';
import { UserEntity } from 'modules/user/entity/users.entity';
import { CreateBlogCommentDto } from './dto/create-comment.dto';
import { UpdateBlogCommentDto } from './dto/update-comment.dto';

@Injectable()
export class BlogCommentService {
  private readonly logger = new Logger(BlogCommentService.name);
  constructor(
    @InjectRepository(BlogComment)
    private readonly blogCommentRepository: Repository<BlogComment>,

    @InjectRepository(Blog)
    private readonly blogRepository: Repository<Blog>,
  ) {}

  // Create a comment for a specific blog
  async create(createBlogCommentDto: CreateBlogCommentDto, userId: number): Promise<BlogComment> {
    const blog = await this.blogRepository.findOne({ where: { blogId: createBlogCommentDto.blogId } });
    if (!blog) {
      throw new NotFoundException('Blog not found');
    }

    this.logger.log(`Creating comment for blog ${blog.blogId}`);
    const newComment = this.blogCommentRepository.create({
      ...createBlogCommentDto,
      userId: userId
    });

    return this.blogCommentRepository.save(newComment);
  }

  // Update a comment by ID
  async update(commentId: string, updateBlogCommentDto: UpdateBlogCommentDto, user: UserEntity): Promise<BlogComment> {
    const comment = await this.blogCommentRepository.findOne({
      where: { commentId },
    //   relations: ['author'],
    });

    if (!comment) {
      throw new NotFoundException('Comment not found');
    }

    if (comment.userId !== user.id) {
      throw new NotFoundException('You are not authorized to update this comment');
    }

    Object.assign(comment, updateBlogCommentDto);
    return this.blogCommentRepository.save(comment);
  }

  // Delete a comment by ID
  async remove(commentId: string, user: UserEntity): Promise<void> {
    const comment = await this.blogCommentRepository.findOne({
      where: { commentId },
    //   relations: ['author'],
    });

    if (!comment) {
      throw new NotFoundException('Comment not found');
    }

    if (comment.userId !== user.id) {
      throw new NotFoundException('You are not authorized to delete this comment');
    }

    await this.blogCommentRepository.remove(comment);
  }

  // Get all comments for a specific blog
  async findAll(blogId: number): Promise<BlogComment[]> {
    return this.blogCommentRepository.find({
      where: { blogId },
    //   relations: ['author'],
    });
  }
}
