package repository

import (
    "api_bb/internal/models"
    "gorm.io/gorm"
)

type CommentRepository interface {
    Create(comment *models.Comment) error
    GetByNewsID(newsID uint) ([]models.Comment, error)
    Delete(id uint) error
    GetByID(id uint) (*models.Comment, error)
}

type commentRepository struct {
    db *gorm.DB
}

func NewCommentRepository(db *gorm.DB) CommentRepository {
    return &commentRepository{db: db}
}

func (r *commentRepository) Create(comment *models.Comment) error {
    return r.db.Create(comment).Error
}

func (r *commentRepository) GetByNewsID(newsID uint) ([]models.Comment, error) {
    var comments []models.Comment
    err := r.db.Preload("Author").Where("news_id = ?", newsID).
        Order("created_at ASC").Find(&comments).Error
    return comments, err
}

func (r *commentRepository) Delete(id uint) error {
    return r.db.Delete(&models.Comment{}, id).Error
}

func (r *commentRepository) GetByID(id uint) (*models.Comment, error) {
    var comment models.Comment
    err := r.db.Preload("Author").Where("id = ?", id).First(&comment).Error
    return &comment, err
}