package middleware

import (
	"fmt"

	"git.kocoder.xyz/kocoded/szuntis-backend/repository"
	"github.com/gofiber/fiber/v2"
	"github.com/google/uuid"
)

type AuthMiddleware struct {
	ar repository.AuthRepository
}

func NewAuthMiddleware(ar repository.AuthRepository) AuthMiddleware {
	return AuthMiddleware{
		ar: ar,
	}
}

func (am AuthMiddleware) IsAuthenticated(ctx *fiber.Ctx) error {
	val := ctx.Cookies("session-token")
	if val == "" {
		fmt.Println(1)
		return ctx.SendStatus(fiber.StatusUnauthorized)
	}
	token, err := uuid.Parse(val)
	if err != nil {
		fmt.Println(2)
		return ctx.SendStatus(fiber.StatusUnauthorized)
	}

	u, err := am.ar.GetUserByToken(ctx.Context(), token)
	if err != nil {
		fmt.Println(3)
		return ctx.SendStatus(fiber.StatusUnauthorized)
	}
	fmt.Println(4)
	ctx.Locals("user", u)
	return ctx.Next()
}
