package middlewares

import (
	"net/http"

	"gauth-central/internal/database"
	"gauth-central/internal/models"

	"github.com/gin-gonic/gin"
)

// AdminMiddleware - Sadece admin rolündeki kullanıcıların erişimini sağlar
func AdminMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		// Get user_id from context (set by AuthMiddleware)
		userID := c.GetString("user_id")
		if userID == "" {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
			c.Abort()
			return
		}

		// Fetch user with roles
		var user models.User
		err := database.DB.Preload("Roles").Where("id = ?", userID).First(&user).Error
		if err != nil {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "User not found"})
			c.Abort()
			return
		}

		// Check if user has admin role
		hasAdminRole := false
		for _, role := range user.Roles {
			if role.Name == "admin" {
				hasAdminRole = true
				break
			}
		}

		if !hasAdminRole {
			c.JSON(http.StatusForbidden, gin.H{"error": "Admin access required"})
			c.Abort()
			return
		}

		c.Next()
	}
}
