package webcontroller

import (
	"errors"
	"fmt"
	"net/http"
	"strings"

	"fornaxian.tech/log"
	"fornaxian.tech/pixeldrain_api_client/pixelapi"
	"fornaxian.tech/util"
	"github.com/julienschmidt/httprouter"
)

func (wc *WebController) serveDirectory(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
	var err error
	var td = wc.newTemplateData(r)
	var path = strings.TrimPrefix(p.ByName("path"), "/")

	// Prevent search engines from indexing this page for privacy reasons
	w.Header().Set("X-Robots-Tag", "noindex, nofollow")

	if path == "" {
		wc.templates.Run(w, r, "404", td)
		return
	}

	var pdapi = wc.api.RealIP(util.RemoteAddress(r)).RealAgent(r.UserAgent())

	if apikey, err := wc.getAPIKey(r); err == nil {
		pdapi = pdapi.Login(apikey)
	}

	node, err := pdapi.GetFilesystemPath(path)
	if err != nil {
		if apiErr, ok := errors.AsType[pixelapi.Error](err); ok {
			// Set the proper response code for the error message
			switch apiErr.StatusCode {
			case "not_found", "path_not_found":
				w.WriteHeader(http.StatusNotFound)
			case "forbidden", "permission_denied":
				w.WriteHeader(http.StatusForbidden)
			case "unavailable_for_legal_reasons":
				w.WriteHeader(http.StatusUnavailableForLegalReasons)
			case "authentication_required":
				http.Redirect(w, r, "/login", http.StatusSeeOther)
				return
			}

			// Let the JS figure it out
			if err = wc.templates.Run(w, r, "wrap", td); err != nil {
				log.Error("Failed to run template: %s", err)
			}
		} else {
			log.Error("Failed to get path: %s", err)
			wc.templates.Run(w, r, "500", td)
		}
		return
	}

	td.Title = fmt.Sprintf("%s ~ Nova", node.Path[node.BaseIndex].Name)
	td.Other = node
	td.OGData = wc.metadataFromFilesystem(r, node)
	err = wc.templates.Run(w, r, "wrap", td)
	if err != nil && !util.IsNetError(err) {
		log.Error("Error executing template filesystem: %s", err)
	}
}
