<?php

namespace Tests\Feature;

use App\Http\Middleware\CacheApiResponse;
use App\Services\ApiResponseCache;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Route;
use Tests\TestCase;

class ApiResponseCacheTest extends TestCase
{
    public function test_it_caches_and_invalidates_api_responses(): void
    {
        config([
            'api_response_cache.enabled' => true,
            'api_response_cache.store' => 'array',
            'api_response_cache.prefix' => 'test-api-response',
            'api_response_cache.routes' => [
                'tests.response-cache' => [
                    'ttl' => 60,
                    'groups' => ['demo'],
                    'shared' => true,
                ],
            ],
        ]);

        Cache::store('array')->flush();

        Route::get('/__test-cache-response', function () {
            static $invocations = 0;

            $invocations++;

            return response()->json([
                'invocations' => $invocations,
            ]);
        })->middleware(CacheApiResponse::class)->name('tests.response-cache');

        $firstResponse = $this->getJson('/__test-cache-response');
        $firstResponse->assertOk();
        $firstResponse->assertHeader('X-Response-Cache', 'MISS');
        $firstResponse->assertJson([
            'invocations' => 1,
        ]);

        $secondResponse = $this->getJson('/__test-cache-response');
        $secondResponse->assertOk();
        $secondResponse->assertHeader('X-Response-Cache', 'HIT');
        $secondResponse->assertJson([
            'invocations' => 1,
        ]);

        app(ApiResponseCache::class)->invalidateGroups(['demo']);

        $thirdResponse = $this->getJson('/__test-cache-response');
        $thirdResponse->assertOk();
        $thirdResponse->assertHeader('X-Response-Cache', 'MISS');
        $thirdResponse->assertJson([
            'invocations' => 2,
        ]);
    }
}
