package blogs

import (
	"context"
	"net/http"

	"fr.latosa-escrima/core"
	"fr.latosa-escrima/core/models"
)

func HandleCategories(w http.ResponseWriter, r *http.Request) {
	var categories []struct {
		Category string `json:"category"`
		Count    int    `json:"count"`
	}
	err := core.DB.NewSelect().
		Model((*models.Blog)(nil)).
		Column("category").
		ColumnExpr("COUNT(*) AS count").
		Where("category IS NOT NULL AND category != ''").
		Group("category").
		// Count the occurrences of each distinct category
		Having("COUNT(category) > 0").
		// Sort the results by the count in descending order
		Order("count DESC").
		Scan(context.Background(), &categories)

	if err != nil {
		core.JSONError{
			Status:  core.Error,
			Message: err.Error(),
		}.Respond(w, http.StatusInternalServerError)
		return
	}

	core.JSONSuccess{
		Status:  core.Success,
		Message: "Categories found.",
		Data:    categories,
	}.Respond(w, http.StatusOK)
}
