package http

import (
	"fmt"
	"github.com/gofiber/fiber/v2"
	"go.uber.org/zap"
	"penahub.gitlab.yandexcloud.net/pena-services/customer/internal/models"
)

type MiddleWare struct {
	logger *zap.Logger
}

func NewMiddleWare(logger *zap.Logger) *MiddleWare {
	return &MiddleWare{
		logger: logger,
	}
}

func (mw *MiddleWare) Error(ctx *fiber.Ctx, status int, message string, rest ...any) error {
	if len(rest) > 0 {
		message = fmt.Sprintf(message, rest...)
	}
	mw.logger.Error(message)
	return ctx.Status(status).JSON(models.ResponseErrorHTTP{
		StatusCode: status,
		Message:    message,
	})
}

func (mw *MiddleWare) ErrorOld(ctx *fiber.Ctx, err error) error {
	mw.logger.Error("error:", zap.Error(err))
	return ctx.Status(fiber.StatusInternalServerError).JSON(models.ResponseErrorHTTP{
		StatusCode: fiber.StatusInternalServerError,
		Message:    err.Error(),
	})
}

func (mw *MiddleWare) NoAuth(ctx *fiber.Ctx) error {
	return mw.Error(ctx, fiber.StatusUnauthorized, "failed to get jwt payload")
}

func (mw *MiddleWare) ExtractUserID(ctx *fiber.Ctx) (string, bool) {
	id, ok := ctx.Context().UserValue(models.AuthJWTDecodedUserIDKey).(string)
	return id, ok
}

func (mw *MiddleWare) ExtractToken(ctx *fiber.Ctx) (string, bool) {
	token, ok := ctx.Context().UserValue(models.AuthJWTDecodedAccessTokenKey).(string)
	return token, ok
}

func (mw *MiddleWare) GetHealth(ctx *fiber.Ctx) error {
	return ctx.Status(fiber.StatusOK).SendString("OK")
}
