package tests

import (
	"testing"
)

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

	// Case 1: Admin modifies User1 (Should Success - admin-only endpoint)
	t.Run("Admin modifies User1", func(t *testing.T) {
		resp := doRequest(t, "PATCH", "/api/users/"+User1ID, map[string]string{
			"nickname": "Edited By Admin",
		}, AdminToken)
		assertStatus(t, resp, 200)

		var data UserResp
		decodeResponse(t, resp, &data)
		if data.Nickname != "Edited By Admin" {
			t.Errorf("Expected nickname 'Edited By Admin', got '%s'", data.Nickname)
		}
	})

	// Case 2: User1 modifies own info via /api/auth/me (Should Success)
	t.Run("User1 modifies own info via /auth/me", func(t *testing.T) {
		resp := doRequest(t, "PATCH", "/api/auth/me", map[string]string{
			"nickname": "Edited By Self",
		}, User1Token)
		assertStatus(t, resp, 200)

		var data UserResp
		decodeResponse(t, resp, &data)
		if data.Nickname != "Edited By Self" {
			t.Errorf("Expected nickname 'Edited By Self', got '%s'", data.Nickname)
		}
	})

	// Case 3: User1 modifies User2 via /api/users (Should Fail - admin only now)
	t.Run("User1 modifies User2 via /api/users", func(t *testing.T) {
		resp := doRequest(t, "PATCH", "/api/users/"+User2ID, map[string]string{
			"nickname": "Hacked By User1",
		}, User1Token)

		// Should fail with 403 Forbidden (or 401 if framework maps ErrNoPermission to 401)
		if resp.Code != 403 && resp.Code != 401 {
			t.Errorf("Expected 403 or 401, got %d. Body: %s", resp.Code, resp.Body.String())
		}
	})

	// Case 4: User1 modifies Admin via /api/users (Should Fail - admin only now)
	t.Run("User1 modifies Admin via /api/users", func(t *testing.T) {
		resp := doRequest(t, "PATCH", "/api/users/"+AdminID, map[string]string{
			"nickname": "Hacked By User1",
		}, User1Token)

		// Should fail with 403 Forbidden (or 401 if framework maps ErrNoPermission to 401)
		if resp.Code != 403 && resp.Code != 401 {
			t.Errorf("Expected 403 or 401, got %d. Body: %s", resp.Code, resp.Body.String())
		}
	})
}
