package repository

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

type NewsRepository interface {
    Create(news *models.News) error
    GetByID(id uint) (*models.News, error)
    GetAll(limit, offset int, category string) ([]models.News, int64, error)
    Update(news *models.News) error
    Delete(id uint) error
    IncrementViews(id uint) error
    GetByAuthor(authorID uint, limit, offset int) ([]models.News, int64, error)
}

type newsRepository struct {
    db *gorm.DB
}

func NewNewsRepository(db *gorm.DB) NewsRepository {
    return &newsRepository{db: db}
}

func (r *newsRepository) Create(news *models.News) error {
    return r.db.Create(news).Error
}

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

func (r *newsRepository) GetAll(limit, offset int, category string) ([]models.News, int64, error) {
    var news []models.News
    var total int64
    
    query := r.db.Preload("Author")
    
    if category != "" && category != "all" {
        query = query.Where("category = ?", category)
    }
    
    // Получаем общее количество
    if err := query.Model(&models.News{}).Count(&total).Error; err != nil {
        return nil, 0, err
    }
    
    // Получаем данные с пагинацией
    err := query.Order("created_at DESC").
        Limit(limit).Offset(offset).
        Find(&news).Error
        
    return news, total, err
}

func (r *newsRepository) Update(news *models.News) error {
    return r.db.Save(news).Error
}

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

func (r *newsRepository) IncrementViews(id uint) error {
    return r.db.Model(&models.News{}).Where("id = ?", id).
        Update("views", gorm.Expr("views + ?", 1)).Error
}

func (r *newsRepository) GetByAuthor(authorID uint, limit, offset int) ([]models.News, int64, error) {
    var news []models.News
    var total int64
    
    query := r.db.Preload("Author").Where("author_id = ?", authorID)
    
    if err := query.Model(&models.News{}).Count(&total).Error; err != nil {
        return nil, 0, err
    }
    
    err := query.Order("created_at DESC").
        Limit(limit).Offset(offset).
        Find(&news).Error
        
    return news, total, err
}