package blogs

import (
	"context"
	"net/http"
	"regexp"

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

func HandleBlog(w http.ResponseWriter, r *http.Request) {
	identifier := r.PathValue("identifier")
	query := "slug = ?"
	if regexp.
		MustCompile(`^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$`).
		MatchString(identifier) {
		query = "blog_id = ?"
	}

	var blog models.Blog
	_, err := core.DB.NewSelect().
		Model(&blog).
		Where(query, identifier).
		Relation("Author").
		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: "Blog retrieved.",
		Data:    blog,
	}.Respond(w, http.StatusOK)
	return
}
