package middleware

import (
	"errors"

	"trustcontact/internal/models"

	"github.com/gofiber/fiber/v2"
	"github.com/gofiber/fiber/v2/middleware/session"
)

func RequireAuth() fiber.Handler {
	return func(c *fiber.Ctx) error {
		if _, ok := CurrentUserFromContext(c); !ok {
			return c.Redirect("/login")
		}
		return c.Next()
	}
}

func RequireAdmin() fiber.Handler {
	return func(c *fiber.Ctx) error {
		user, ok := CurrentUserFromContext(c)
		if !ok {
			return c.Redirect("/login")
		}
		if user.Role != models.RoleAdmin {
			return c.Status(fiber.StatusForbidden).Redirect("/forbidden")
		}
		return c.Next()
	}
}

func SetSessionUserID(c *fiber.Ctx, userID string) error {
	store, ok := c.Locals(contextStoreKey).(*session.Store)
	if !ok || store == nil {
		return errors.New("session store not available")
	}

	sess, err := store.Get(c)
	if err != nil {
		return err
	}

	sess.Set(sessionUserIDKey, userID)
	return sess.Save()
}

func ClearSessionUser(c *fiber.Ctx) error {
	store, ok := c.Locals(contextStoreKey).(*session.Store)
	if !ok || store == nil {
		return errors.New("session store not available")
	}

	sess, err := store.Get(c)
	if err != nil {
		return err
	}

	sess.Delete(sessionUserIDKey)
	return sess.Save()
}
