package handlers

import (
	"net/http"

	"git.haelnorr.com/h/golib/cookies"
	"git.haelnorr.com/h/golib/hws"
	"github.com/pkg/errors"

	"git.haelnorr.com/h/oslstats/internal/config"
	"git.haelnorr.com/h/oslstats/internal/discord"
	"git.haelnorr.com/h/oslstats/internal/store"
	"git.haelnorr.com/h/oslstats/pkg/oauth"
)

func Login(server *hws.Server, cfg *config.Config, st *store.Store, discordAPI *discord.APIClient) http.Handler {
	return http.HandlerFunc(
		func(w http.ResponseWriter, r *http.Request) {
			cookies.SetPageFrom(w, r, cfg.HWSAuth.TrustedHost)
			attempts, exceeded, track := st.TrackRedirect(r, "/login", 5)

			if exceeded {
				err := errors.Errorf(
					"login redirect loop detected after %d attempts | ip=%s ua=%s path=%s first_seen=%s",
					attempts,
					track.IP,
					track.UserAgent,
					track.Path,
					track.FirstSeen.Format("2006-01-02T15:04:05Z07:00"),
				)

				st.ClearRedirectTrack(r, "/login")

				throwError(
					server,
					w,
					r,
					http.StatusBadRequest,
					"Login failed: Too many redirect attempts. Please clear your browser cookies and try again.",
					err,
					"warn",
				)
				return
			}

			state, uak, err := oauth.GenerateState(cfg.OAuth, "login")
			if err != nil {
				throwInternalServiceError(server, w, r, "Failed to generate state token", err)
				return
			}
			oauth.SetStateCookie(w, uak, cfg.HWSAuth.SSL)

			link, err := discordAPI.GetOAuthLink(state)
			if err != nil {
				throwInternalServiceError(server, w, r, "An error occurred trying to generate the login link", err)
				return
			}
			st.ClearRedirectTrack(r, "/login")

			http.Redirect(w, r, link, http.StatusSeeOther)
		},
	)
}
