package server

import (
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
	domain "github.com/haydenhargreaves/Potion/internal/domain/server"
	"github.com/haydenhargreaves/Potion/internal/templates/components"
)

// GoogleLogin directs the user to Googles select user login page. Once the user has selected an
// account, they will be directed to the GoogleCallback handler where the main logic resides.
func (s *Server) GoogleLoginHandler(ctx *gin.Context) {
	url := s.deps.AuthService.GetGoogleAuthUrl()
	ctx.Redirect(http.StatusSeeOther, url)
}

// GoogleCallback is the callback handler when the user successfully logs in with their Google
// account. They will be directed here and a JWT is generated. This JWT is stored in the users
// cookies and will be used by protected routes to validate their login status.
func (s *Server) GoogleCallbackHandler(ctx *gin.Context) {
	var (
		state string = ctx.Query("state")
		code  string = ctx.Query("code")
	)

	if jwt, err := s.deps.AuthService.GoogleAuthSuccess(state, code); err != nil {
		components.RenderErrorBanner(ctx, err.Error())
		ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
	} else {
		s.SetCookie(ctx, "jwt_token", jwt, time.Hour*24*7)
		ctx.Redirect(http.StatusSeeOther, "/")
	}
}

// Logout removes the token from the user's browser. Effectively "logging them out." Routes that
// require authentication will require the user to sign back in before accessing them again.
// This route will direct the user back to the home page.
func (s *Server) LogoutHandler(ctx *gin.Context) {
	s.SetCookie(ctx, "jwt_token", "", -1)
	s.SetCookie(ctx, "search-filters", "", -1)
	ctx.Redirect(http.StatusSeeOther, domain.WEB_HOME)
}

