package middlewares

import (
	"net/url"

	"github.com/gofiber/fiber/v2"
	"github.com/gookit/validate"
	"github.com/sujit-baniya/fiber-boilerplate/pkg/auth"
	"github.com/sujit-baniya/fiber-boilerplate/pkg/models"
)

func RedirectToHomePageOnLogin(c *fiber.Ctx) error {
	if auth.IsLoggedIn(c) {
		user, err := auth.User(c)
		if err == nil && user != nil && user.Role.HomeUrl != "" {
			return c.Redirect(user.Role.HomeUrl)
		}
		return c.Redirect("/app/servidor")
	}
	// Si tiene sesión de portal activa, ir al portal
	if user, err := auth.PortalUser(c); err == nil && user != nil {
		return c.Redirect("/portal/dashboard")
	}
	return c.Next()
}

func ValidateLoginPost(c *fiber.Ctx) error {
	var login models.Login
	if err := c.BodyParser(&login); err != nil {
		return c.Redirect("/login?error=" + url.QueryEscape(err.Error()))
	}
	v := validate.Struct(login)
	if !v.Validate() {
		return c.Redirect("/login?error=" + url.QueryEscape(v.Errors.One()))
	}

	user, err := login.CheckLogin()
	if err != nil {
		// Si no está en users, intentar en portal_users
		if portalUser, pErr := models.CheckPortalLogin(login.NombreUsuario, login.Password); pErr == nil {
			if sErr := auth.SetPortalSession(c, portalUser.ID); sErr != nil {
				return c.Redirect("/login?error=Error+interno")
			}
			return c.Redirect("/portal/dashboard")
		}
		return c.Redirect("/login?error=" + url.QueryEscape(err.Error()))
	}

	c.Locals("user", user)
	return c.Next()
}
