package api

import (
	"net/http"

	"code.osinet.fr/fgm/kurz/domain"
	"github.com/gorilla/mux"
)

// HandleGetShort() handles GET /<short>.
func HandleGetShort(w http.ResponseWriter, r *http.Request) {
	short, ok := mux.Vars(r)["short"]
	if !ok {
		w.WriteHeader(http.StatusBadRequest)
		return
	}

	target, err := domain.GetTargetURL(short)
	// Happy path.
	if err == nil {
		w.Header().Set("Location", target)
		w.WriteHeader(http.StatusTemporaryRedirect)
		return
	}

	// Very sad path.
	domainErr, ok := err.(domain.Error)
	if !ok {
		// All errors return by the API should be domain-specific errors.
		w.WriteHeader(http.StatusInternalServerError)
		return
	}

	// Normal sad paths.
	var status int
	switch domainErr.Kind {
	case domain.ShortNotFound:
		status = http.StatusNotFound
	case domain.TargetBlockedError:
		status = http.StatusForbidden
	case domain.TargetCensoredError:
		status = http.StatusUnavailableForLegalReasons
	default:
		// TargetInvalid is not supposed to happen in this case, so it is an internal error too.
		status = http.StatusInternalServerError
	}

	w.WriteHeader(status)
}