<?php

use App\Http\Middleware\CheckLegalAgreement;
use App\Models\User;
use App\Models\UserConsent;
use App\Services\SystemConfig\SystemConfigService;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Route;

beforeEach(function () {
    // Pest.php disables CheckLegalAgreement globally for Feature tests — re-enable it here.
    $this->withMiddleware(CheckLegalAgreement::class);

    $ref = new ReflectionClass(SystemConfigService::class);
    $prop = $ref->getProperty('resolvedSettings');
    $prop->setAccessible(true);
    $prop->setValue(null, null);
    Cache::flush();

    Route::middleware(['web', 'auth', CheckLegalAgreement::class])
        ->get('/__legal-probe', fn () => response('ok'));
});

function setLegalVersion(string $prefix, int $version): void
{
    app(SystemConfigService::class)->update(["{$prefix}_document_version" => $version]);
}

test('guest is unaffected by middleware', function () {
    $this->get('/__legal-probe')->assertRedirect('/login');
});

test('user without consent is redirected to re-agree', function () {
    setLegalVersion('tos', 1);
    setLegalVersion('pdp', 1);
    $user = User::factory()->create();

    $this->actingAs($user)->get('/__legal-probe')
        ->assertRedirect(route('legal.re-agree', absolute: false));
});

test('user with current consent passes through', function () {
    setLegalVersion('tos', 1);
    setLegalVersion('pdp', 1);
    $user = User::factory()->create();
    UserConsent::create(['user_id' => $user->id, 'consent_type' => 'tos', 'version_id' => 1, 'ip_address' => '127.0.0.1']);
    UserConsent::create(['user_id' => $user->id, 'consent_type' => 'privacy', 'version_id' => 1, 'ip_address' => '127.0.0.1']);

    $this->actingAs($user)->get('/__legal-probe')->assertOk();
});

test('user with outdated consent is redirected', function () {
    setLegalVersion('tos', 2);
    setLegalVersion('pdp', 2);
    $user = User::factory()->create();
    UserConsent::create(['user_id' => $user->id, 'consent_type' => 'tos', 'version_id' => 1, 'ip_address' => '127.0.0.1']);
    UserConsent::create(['user_id' => $user->id, 'consent_type' => 'privacy', 'version_id' => 1, 'ip_address' => '127.0.0.1']);

    $this->actingAs($user)->get('/__legal-probe')
        ->assertRedirect(route('legal.re-agree', absolute: false));
});
