// internal/middleware/role_middleware.go
package middleware

import (
	"lost-and-found/internal/models"
	"lost-and-found/internal/utils"
	"net/http"

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

func RequirePermission(requiredPerm string) gin.HandlerFunc {
	return func(ctx *gin.Context) {
		// 1. Ambil object user dari context (diset oleh JWTMiddleware)
		userObj, exists := ctx.Get("user")
		if !exists {
			utils.ErrorResponse(ctx, http.StatusUnauthorized, "Authentication required", "")
			ctx.Abort()
			return
		}

		user := userObj.(*models.User)

		// 2. Cek Permission menggunakan method helper di model User
		// Pastikan method HasPermission sudah ditambahkan di internal/models/user.go
		if !user.HasPermission(requiredPerm) {
			utils.ErrorResponse(ctx, http.StatusForbidden, "Insufficient permissions", "Missing permission: "+requiredPerm)
			ctx.Abort()
			return
		}

		ctx.Next()
	}
}

// RequireRole checks if user has required role
func RequireRole(allowedRoles ...string) gin.HandlerFunc {
	return func(ctx *gin.Context) {
		userObj, exists := ctx.Get("user")
		if !exists {
			utils.ErrorResponse(ctx, http.StatusUnauthorized, "Authentication required", "")
			ctx.Abort()
			return
		}

		user := userObj.(*models.User)
		userRole := user.Role.Name

		// Check if user has allowed role
		hasRole := false
		for _, role := range allowedRoles {
			if userRole == role {
				hasRole = true
				break
			}
		}

		if !hasRole {
			utils.ErrorResponse(ctx, http.StatusForbidden, "Insufficient permissions", "")
			ctx.Abort()
			return
		}

		ctx.Next()
	}
}

// RequireAdmin middleware (admin only)
func RequireAdmin() gin.HandlerFunc {
	return RequireRole(models.RoleAdmin)
}

// RequireManager middleware (manager and admin)
func RequireManager() gin.HandlerFunc {
	return RequireRole(models.RoleAdmin, models.RoleManager)
}

// RequireUser middleware (all authenticated users)
func RequireUser() gin.HandlerFunc {
	return RequireRole(models.RoleAdmin, models.RoleManager, models.RoleUser)
}