// tofuproxy -- flexible HTTP/HTTPS proxy, TLS terminator, X.509 TOFU
//              manager, WARC/geminispace browser
// Copyright (C) 2021-2026 Sergey Matveev <stargrave@stargrave.org>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, version 3 of the License.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

package rounds

import (
	"fmt"
	"net/http"
	"path/filepath"
	"strings"

	"go.stargrave.org/tofuproxy/fifos"
)

var imageExts = map[string]struct{}{
	".apng": {},
	".avif": {},
	".gif":  {},
	".heic": {},
	".jp2":  {},
	".jpeg": {},
	".jpg":  {},
	".jxl":  {},
	".mng":  {},
	".png":  {},
	".svg":  {},
	".tif":  {},
	".tiff": {},
	".webp": {},
}

func isFeeder(req *http.Request) bool {
	return strings.Contains(req.Header.Get("User-Agent"), "stargrave.org-feeder/")
}

func RoundRedirectHTML(
	host string,
	resp *http.Response,
	w http.ResponseWriter,
	req *http.Request,
) (bool, error) {
	if req.Method != http.MethodGet {
		return true, nil
	}
	var redirType string
	switch resp.StatusCode {
	case http.StatusMovedPermanently, http.StatusPermanentRedirect:
		redirType = "permanent"
	case http.StatusFound, http.StatusSeeOther, http.StatusTemporaryRedirect:
		if isFeeder(req) {
			return true, nil
		}
		if _, ok := imageExts[filepath.Ext(req.URL.Path)]; ok {
			return true, nil
		}
		redirType = "temporary"
	default:
		return true, nil
	}
	resp.Body.Close()
	w.Header().Add("Content-Type", "text/html")
	w.WriteHeader(http.StatusOK)
	location := resp.Header.Get("Location")
	fmt.Fprintf(
		w, `<!DOCTYPE html>
<html><head><title>%d %s: %s redirection</title></head>
<body><a href="%s">%s</a></body></html>`,
		resp.StatusCode, http.StatusText(resp.StatusCode),
		redirType, location, location,
	)
	fifos.LogRedir <- fmt.Sprintf(
		"%s %s\t%s\t%s", req.Method, req.URL, resp.Status, location,
	)
	return false, nil
}
