package shortcodes

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

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

func HandleShortcode(w http.ResponseWriter, r *http.Request) {
	code := r.PathValue("shortcode")
	var shortcode models.Shortcode
	count, err := core.DB.NewSelect().
		Model(&shortcode).
		Where("code = ?", code).
		Relation("Media").
		Limit(1).
		ScanAndCount(context.Background())

	if count == 0 {
		core.JSONSuccess{
			Status:  core.Success,
			Message: "Shortcode has not been found",
		}.Respond(w, http.StatusNotFound)
		return
	}

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

	scheme := "http"
	if r.TLS != nil { // Check if the request is over HTTPS
		scheme = "https"
	}

	// Extract the host
	host := r.Host
	baseURL := fmt.Sprintf("%s://%s", scheme, host)
	if os.Getenv("ENVIRONMENT") != "DEV" {
		baseURL += "/api"
	}
	if shortcode.Media != nil {
		shortcode.Media.URL = fmt.Sprintf("%s/media/%s/file", baseURL, shortcode.Media.ID)
	}
	core.JSONSuccess{
		Status:  core.Success,
		Message: "Shortcode found",
		Data:    shortcode,
	}.Respond(w, http.StatusOK)
}
