<?php

namespace Tests\Feature;

use App\Models\User;
use App\Services\SyncService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\RateLimiter;
use Tests\TestCase;

class SyncRateLimiterTest extends TestCase
{
    use RefreshDatabase;

    protected SyncService $syncService;

    protected function setUp(): void
    {
        parent::setUp();
        $this->seed();
        $this->syncService = app(SyncService::class);
    }

    public function test_sync_service_blocks_rapid_double_sync(): void
    {
        $admin = User::where('email', 'admin@smkn1gunungagung.sch.id')->first();
        $this->actingAs($admin);

        RateLimiter::clear("sync-all-user-{$admin->id}");

        // Eksekusi pertama
        $res1 = $this->syncService->syncAllMachines();
        $this->assertEquals(6, $res1['total_machines']);

        // Eksekusi kedua beruntun (harus diblokir oleh Rate Limiter)
        $res2 = $this->syncService->syncAllMachines();
        $this->assertEquals(0, $res2['total_machines']);
        $this->assertFalse($res2['success']);
        $this->assertStringContainsString('Silakan tunggu', $res2['message']);
    }
}
