package middlewares

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

// PortalAuth protege las rutas del portal de clientes.
// Si no hay sesión activa, redirige a /portal/login.
func PortalAuth() fiber.Handler {
	return func(c *fiber.Ctx) error {
		user, err := auth.PortalUser(c)
		if err != nil || user == nil {
			return c.Redirect("/portal/login")
		}
		c.Locals("portalUser", user)
		return c.Next()
	}
}

// LoadPortalUserMiddleware carga el portal user en locals (sin redirigir).
func LoadPortalUserMiddleware(c *fiber.Ctx) error {
	user, err := auth.PortalUser(c)
	if err == nil && user != nil {
		c.Locals("portalUser", user)
	}
	return c.Next()
}

// PortalUserFromLocals extrae el portal user del contexto (helper para controladores).
func PortalUserFromLocals(c *fiber.Ctx) *models.PortalUser {
	u, _ := c.Locals("portalUser").(*models.PortalUser)
	return u
}
