package blogs

import (
	"context"
	"fmt"
	"net/http"

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

func HandleGetBlogs(w http.ResponseWriter, r *http.Request) {
	category := r.URL.Query().Get("category")
	var blog []models.Blog
	q := core.DB.NewSelect().
		Model(&blog).
		Relation("Author")

	if len(category) > 0 {
		q.Where("category = ?", category)
	}

	count, err := q.ScanAndCount(context.Background())
	if err != nil {
		core.JSONError{
			Status:  core.Error,
			Message: err.Error(),
		}.Respond(w, http.StatusNotAcceptable)
		return
	}

	core.JSONSuccess{
		Status:  core.Success,
		Message: fmt.Sprintf("%d blogs objects sent", count),
		Data:    blog,
	}.Respond(w, http.StatusOK)
	return
}
