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

/**
 * BlogRepository implementáció Prisma-val
 * Implementálja az IBlogRepository interface-t
 */
export class BlogRepository extends IBlogRepository {
  async findById(id) {
    const blog = await prisma.blog.findUnique({
      where: { id },
      include: {
        author: {
          select: {
            id: true,
            username: true,
            email: true
          }
        }
      }
    });
    return blog ? new Blog(blog) : null;
  }

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

  async findAll(options = {}) {
    const { publishedOnly = false, limit, offset } = options;
    
    const where = publishedOnly ? { published: true } : {};
    
    const blogs = await prisma.blog.findMany({
      where,
      include: {
        author: {
          select: {
            id: true,
            username: true,
            email: true
          }
        }
      },
      orderBy: { createdAt: 'desc' },
      take: limit,
      skip: offset
    });
    return blogs.map(blog => new Blog(blog));
  }

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

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

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

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