package matrix

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

	"git.devvul.com/asara/gologger"
	"git.devvul.com/asara/well-goknown/config"
)

type matrixServerWellKnown struct {
	WellKnownAddress string `json:"m.server"`
}

type matrixBaseUrl struct {
	BaseUrl string `json:"base_url"`
}

type matrixIdentityServer struct {
	BaseUrl string `json:"base_url,omitempty"`
}

type msc3575address struct {
	Url string `json:"url,omitempty"`
}

type matrixClientWellKnown struct {
	Homeserver     *matrixBaseUrl        `json:"m.homeserver"`
	IdentityServer *matrixIdentityServer `json:"m.identity_server,omitempty"`
	Msc3575        *msc3575address       `json:"org.matrix.msc3575.proxy,omitempty"`
}

func MatrixServer(w http.ResponseWriter, req *http.Request) {
	l := gologger.Get(config.GetConfig().LogLevel).With().Caller().Logger()
	// uses an environment variable for now
	wellKnownAddr := fmt.Sprintf("%s:8448", config.GetConfig().MatrixWellKnownAddress)
	if wellKnownAddr == "" {
		l.Debug().Str("path", "matrix/server").Msg("matrix well known address unset")
		http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
		return
	}

	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	wellKnown := &matrixServerWellKnown{
		WellKnownAddress: wellKnownAddr,
	}
	json.NewEncoder(w).Encode(wellKnown)
}

func MatrixClient(w http.ResponseWriter, req *http.Request) {
	l := gologger.Get(config.GetConfig().LogLevel).With().Caller().Logger()
	m := &matrixClientWellKnown{}

	wellKnownAddr := config.GetConfig().MatrixWellKnownAddress
	// no matrix config set
	if wellKnownAddr == "" {
		l.Debug().Str("path", "matrix/client").Msg("matrix well known address unset")
		http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
		return
	}

	m.Homeserver = &matrixBaseUrl{
		BaseUrl: fmt.Sprintf("https://%s", wellKnownAddr),
	}

	identityServer := config.GetConfig().MatrixIdentityServer
	if identityServer != "" {
		m.IdentityServer = &matrixIdentityServer{
			BaseUrl: identityServer,
		}
	}

	msc3575 := config.GetConfig().MatrixMsc3575Address
	if msc3575 != "" {
		m.Msc3575 = &msc3575address{
			Url: msc3575,
		}
	}

	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	json.NewEncoder(w).Encode(m)
}