package middleware

import (
	"github.com/gofiber/fiber/v2"

	"wucher/internal/service"
	"wucher/internal/shared/pkg/appctx"
	"wucher/internal/shared/pkg/apperrorsx"
)

func AuthRequired(svc *service.AuthService) fiber.Handler {
	return func(c *fiber.Ctx) error {
		if svc == nil {
			e := apperrorsx.New(apperrorsx.ErrUserUnauthorized)
			e.Message = "auth service not configured"
			return apperrorsx.Write(c, e)
		}

		ctx := c.UserContext()
		for _, candidate := range service.CookieValues(c.Get(fiber.HeaderCookie), svc.AccessCookieName()) {
			userID, err := svc.ParseAccessToken(ctx, candidate)
			if err == nil {
				c.Locals("user_id", userID)
				c.SetUserContext(appctx.WithUserID(ctx, userID))
				return c.Next()
			}
		}
		return apperrorsx.Write(c, apperrorsx.New(apperrorsx.ErrTokenInvalid))
	}
}
