package newsrepository

import newsdomain "legalgo-BE-go/internal/domain/news"

func (a *accessor) GetAll(filter newsdomain.NewsFilter) ([]newsdomain.News, error) {
	var news []newsdomain.News
	query := a.db.
		Preload("Tags").
		Preload("Categories").
		Preload("Author").
		Joins("LEFT JOIN content_logs ON content_logs.content_id = news.id")

	if len(filter.Category) > 0 {
		query = query.Joins("JOIN news_categories nc ON nc.news_id = news.id").
			Where("nc.category_id IN (?)", filter.Category)
	}

	if len(filter.Tags) > 0 {
		query = query.Joins("JOIN news_tags nt ON nt.news_id = news.id").
			Where("nt.tag_id IN (?)", filter.Tags)
	}

	query.
		Select("news.*, COUNT(content_logs.content_id) as clicked").
		Group("news.id").
		Order("news.created_at DESC")

	if err := query.
		Find(&news).Error; err != nil {
		return nil, err
	}

	return news, nil
}
