package tests

import (
	"context"
	"testing"

	"github.com/veypi/vbase/auth"
	"github.com/veypi/vbase/cfg"
	"github.com/veypi/vbase/models"
)

func TestRoleApiAccess(t *testing.T) {
	ensureUsers(t)

	ctx := context.Background()

	// Ensure Admin has * permission
	// Clean up any previous permissions for Admin
	cfg.DB().Where("user_id = ?", AdminID).Delete(&models.Permission{})

	// Grant Admin * permission
	if err := cfg.Auth.Grant(ctx, AdminID, "*", auth.LevelAdmin); err != nil {
		t.Fatalf("Failed to grant admin permission: %v", err)
	}

	// 1. Admin Access (Wildcard *)
	t.Run("Admin_Access_Role_List", func(t *testing.T) {
		resp := doRequest(t, "GET", "/api/roles", nil, AdminToken)
		assertStatus(t, resp, 200)
	})

	// 2. User Access (No Permission)
	t.Run("User_NoAccess_Role_List", func(t *testing.T) {
		// Ensure User1 has NO role:* permission
		cfg.DB().Where("user_id = ?", User1ID).Delete(&models.Permission{})

		resp := doRequest(t, "GET", "/api/roles", nil, User1Token)
		// Should be 403 or 401
		if resp.Code != 403 && resp.Code != 401 {
			t.Errorf("Expected 403/401, got %d", resp.Code)
		}
	})

	// 3. User Access (With Permission)
	t.Run("User_WithPermission_Role_List", func(t *testing.T) {
		// Grant role:* (Read) to User1
		if err := cfg.Auth.Grant(ctx, User1ID, "role:*", auth.LevelRead); err != nil {
			t.Fatalf("Failed to grant role permission: %v", err)
		}

		resp := doRequest(t, "GET", "/api/roles", nil, User1Token)
		assertStatus(t, resp, 200)
	})
}
