/*
 * SPDX-FileCopyrightText: 2023 jordi fita mas <jfita@peritasoft.com>
 * SPDX-License-Identifier: AGPL-3.0-only
 */

package http

import (
	"encoding/json"
	"net/http"
)

const (
	HxLocation           = "HX-Location"
	HxRedirect           = "HX-Redirect"
	HxRequest            = "HX-Request"
	HxTriggerAfterSettle = "HX-Trigger-After-Settle"
)

func Relocate(w http.ResponseWriter, r *http.Request, url string, code int) {
	if IsHTMxRequest(r) {
		w.Header().Set(HxLocation, MustMarshalHTMxLocation(&HTMxLocation{
			Path:   url,
			Target: "main",
		}))
		w.WriteHeader(http.StatusNoContent)
	} else {
		http.Redirect(w, r, url, code)
	}
}

func Redirect(w http.ResponseWriter, r *http.Request, url string, code int) {
	if IsHTMxRequest(r) {
		w.Header().Set(HxRedirect, url)
		w.WriteHeader(http.StatusNoContent)
	} else {
		http.Redirect(w, r, url, code)
	}
}

func TriggerAfterSettle(w http.ResponseWriter, trigger string) {
	w.Header().Set(HxTriggerAfterSettle, trigger)
}

func IsHTMxRequest(r *http.Request) bool {
	return r.Header.Get(HxRequest) == "true"
}

type HTMxLocation struct {
	Path   string `json:"path"`
	Target string `json:"target"`
}

func MustMarshalHTMxLocation(location *HTMxLocation) string {
	data, err := json.Marshal(location)
	if err != nil {
		panic(err)
	}
	return string(data)
}
