import { IBlogRepository } from '../../domain/repositories/IBlogRepository.js';
import { Blog } from '../../domain/models/Blog.js';
import { prisma } from '../database/prisma.js';

export class BlogRepository extends IBlogRepository {
  async findById(id) {
    const blog = await prisma.blog.findUnique({
      where: { id },
      include: { author: true }
    });
    return blog ? new Blog(blog) : null;
  }

  async findAll() {
    const blogs = await prisma.blog.findMany({
      include: { author: true },
      orderBy: { createdAt: 'desc' }
    });
    return blogs.map(blog => new Blog(blog));
  }

  async findByAuthorId(authorId) {
    const blogs = await prisma.blog.findMany({
      where: { authorId },
      include: { author: true },
      orderBy: { createdAt: 'desc' }
    });
    return blogs.map(blog => new Blog(blog));
  }

  async create(blogData) {
    const blog = await prisma.blog.create({
      data: blogData,
      include: { author: true }
    });
    return new Blog(blog);
  }

  async update(id, blogData) {
    const blog = await prisma.blog.update({
      where: { id },
      data: blogData,
      include: { author: true }
    });
    return new Blog(blog);
  }

  async delete(id) {
    await prisma.blog.delete({
      where: { id }
    });
    return true;
  }
}
