package http

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

	"github.com/go-ap/activitypub"

	"source.toby3d.me/toby3d/home/internal/common"
	"source.toby3d.me/toby3d/home/internal/domain"
)

type (
	Handler struct{}

	/* TODO(toby3d)
	Profile struct {
		*activitypub.Person

		// Mastodon related

		// Pinned posts. See [Featured collection].
		//
		// [Featured collection]: https://docs.joinmastodon.org/spec/activitypub/#featured
		Featured []interface{} `json:"featured"`

		// Required for Move activity.
		AlsoKnownAs []string `json:"alsoKnownAs"`

		// Will be shown as a locked account.
		ManuallyApprovesFollowers bool `json:"manuallyApprovesFollowers"`

		// Will be shown in the profile directory.
		// See [Discoverability flag].
		//
		// [Discoverability flag]: https://docs.joinmastodon.org/spec/activitypub/#discoverable
		Discoverable bool `json:"discoverable"`
	}
	*/
)

func NewHandler() *Handler {
	return &Handler{}
}

func (Handler) HandleProfile(site *domain.Site) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
		langRef := activitypub.LangRef(site.DefaultLanguage.Lang())
		person := activitypub.PersonNew(activitypub.IRI(site.BaseURL.String()))
		person.URL = person.ID
		person.Name.Add(activitypub.LangRefValueNew(langRef, "Maxim Lebedev"))
		person.Summary.Add(activitypub.LangRefValueNew(langRef, "Creative dude from russia"))
		person.PreferredUsername.Add(activitypub.LangRefValueNew(langRef, "toby3d"))
		person.Published = time.Date(2009, time.February, 0, 0, 0, 0, 0, time.UTC)

		w.Header().Set(common.HeaderContentType, common.MIMEApplicationActivityJSONCharsetUTF8)
		_ = json.NewEncoder(w).Encode(person)
	})
}

func (Handler) HandleEntry(site *domain.Site, entry *domain.Entry) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
		resp := activitypub.ObjectNew(activitypub.NoteType)
		resp.ID = activitypub.ID(site.BaseURL.JoinPath(entry.File.Path()).String())
		resp.Content.Add(activitypub.LangRefValueNew(activitypub.LangRef(entry.Language.Lang()),
			string(entry.Content)))

		w.Header().Set(common.HeaderContentType, common.MIMEApplicationActivityJSONCharsetUTF8)
		_ = json.NewEncoder(w).Encode(resp)
	})
}
