package server

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

	"github.com/rs/zerolog"
	"git.mstar.dev/mstar/linstrom/storage"
	"gorm.io/gorm"
)

// Mount under /.well-known/webfinger
func webfingerHandler(w http.ResponseWriter, r *http.Request) {
	logger := zerolog.Ctx(r.Context())
	store := storage.Storage{}

	requestedResource := r.FormValue("resource")
	if requestedResource == "" {
		http.Error(w, "bad request. Include \"resource\" parameter", http.StatusBadRequest)
		logger.Debug().Msg("Resource parameter missing. Cancelling")
		return
	}
	accName := strings.TrimPrefix(requestedResource, "acc:")
	acc, err := store.FindAccountByFullHandle(accName)
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			http.Error(w, "account not found", http.StatusNotFound)
			logger.Debug().Str("account-name", accName).Msg("Account not found")
		} else {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			logger.Error().Err(err).Msg("Error while searching for account")
			return
		}
	}
	fmt.Fprint(w, acc)
}
