package server

import (
	"fmt"
	"net/http"

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

func (s *Server) GetUserRecipesHandler(ctx *gin.Context) {
	// Ensure user is logged in with a valid account
	user := s.deps.UserService.GetAuthenicatedUser(ctx)
	if user == nil {
		// Log (stale) user out
		s.SetCookie(ctx, "jwt_token", "", -1)
		s.SetCookie(ctx, "search-filters", "", -1)
	}

	// Ensure logged in
	if !domain.IsLoggedIn(ctx) || user == nil {
		components.RenderErrorBanner(ctx, "User is not authorized to access this endpoint. Please login to continue.")
		ctx.JSON(http.StatusUnauthorized, gin.H{
			"status":  http.StatusUnauthorized,
			"message": "User is not authorized to access this endpoint. Please login to continue.",
			"recipes": nil,
		})
		return
	}

	recipes, err := s.deps.RecipeService.GetUserRecipes(user.Id)
	if err != nil {
		components.RenderErrorBanner(ctx, fmt.Sprintf("Could not get user recipes. %s", err.Error()))
		ctx.JSON(http.StatusBadRequest, gin.H{
			"status":  http.StatusBadRequest,
			"message": fmt.Sprintf("Could not get user recipes. %s", err.Error()),
			"recipes": nil,
		})
		return
	}

	ctx.JSON(http.StatusOK, gin.H{
		"status":  http.StatusOK,
		"message": "User recipes successfully retrieved.",
		"recipes": recipes,
	})
}

func (s *Server) GetUserFavoriteRecipesHandler(ctx *gin.Context) {
	// Ensure user is logged in with a valid account
	user := s.deps.UserService.GetAuthenicatedUser(ctx)
	if user == nil {
		// Log (stale) user out
		s.SetCookie(ctx, "jwt_token", "", -1)
		s.SetCookie(ctx, "search-filters", "", -1)
	}

	// Ensure logged in
	if !domain.IsLoggedIn(ctx) || user == nil {
		components.RenderErrorBanner(ctx, "User is not authorized to access this endpoint. Please login to continue.")
		ctx.JSON(http.StatusUnauthorized, gin.H{
			"status":  http.StatusUnauthorized,
			"message": "User is not authorized to access this endpoint. Please login to continue.",
			"recipes": nil,
		})
		return
	}

	recipes, err := s.deps.RecipeService.GetUserFavoriteRecipes(user.Id)
	if err != nil {
		components.RenderErrorBanner(ctx, fmt.Sprintf("Could not get favorite recipes. %s", err.Error()))
		ctx.JSON(http.StatusBadRequest, gin.H{
			"status":  http.StatusBadRequest,
			"message": fmt.Sprintf("Could not get favorite recipes. %s", err.Error()),
			"recipes": nil,
		})
		return
	}

	ctx.JSON(http.StatusOK, gin.H{
		"status":  http.StatusOK,
		"message": "User recipes successfully retrieved.",
		"recipes": recipes,
	})

}
