package newsrepository

import (
	newsdomain "legalgo-BE-go/internal/domain/news"
	timeutils "legalgo-BE-go/internal/utilities/time_utils"
)

type is_active string

const (
	active    is_active = "true"
	notActive is_active = "false"
)

func (a *accessor) GetAll(filter newsdomain.NewsFilter) ([]newsdomain.NewsResponse, error) {
	var news []newsdomain.NewsResponse
	query := a.db.Table("news").
		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)
	}

	if filter.Active == string(active) {
		query = query.Where("news.live_at <= ?", timeutils.Now())
	}

	if filter.Search != "" {
		query = query.Where("news.title ILIKE ?", "%"+filter.Search+"%")
	}

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

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

	return news, nil
}
