package main

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

	"github.com/go-chi/chi/v5"
)

func WebFingerHandler(wf *Webfinger) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		requestedResource := r.URL.Query().Get("resource")
		res, err := wf.FingerResource(requestedResource)
		if err != nil {
			w.WriteHeader(http.StatusNotFound)
			w.Write([]byte(`{"error": "account not found"}`))
			return
		}
		b, err := json.Marshal(res)
		if err != nil {
			w.WriteHeader(http.StatusInternalServerError)
			return
		}
		w.Write(b)
	}
}

func ProfileHandler(pp *ProfileProvider) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		userID := chi.URLParam(r, "user")
		res, err := pp.Get(userID)
		if err != nil {
			w.WriteHeader(http.StatusNotFound)
			w.Write([]byte(`{"error": "account not found"}`))
			return
		}
		b, err := json.Marshal(res)
		if err != nil {
			w.WriteHeader(http.StatusInternalServerError)
			return
		}
		w.Write(b)
	}
}
