<?php

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

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

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

function setExpirySetting(int $days): void
{
    app(SystemConfigService::class)->update(['password_expiry_days' => $days]);
}

test('user with fresh password passes through', function () {
    setExpirySetting(30);
    $user = User::factory()->create();
    DB::table('users')->where('id', $user->id)
        ->update(['password_changed_at' => now()->subDays(5)]);

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

test('user with expired password is redirected to profile', function () {
    setExpirySetting(30);
    $user = User::factory()->create();
    DB::table('users')->where('id', $user->id)
        ->update(['password_changed_at' => now()->subDays(40)]);

    $this->actingAs($user->fresh())->get('/__pwd-probe')
        ->assertRedirect(route('profile.edit', absolute: false))
        ->assertSessionHas('warning');
});

test('expiry disabled (0 days) never redirects', function () {
    setExpirySetting(0);
    $user = User::factory()->create();
    DB::table('users')->where('id', $user->id)
        ->update(['password_changed_at' => now()->subYears(2)]);

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

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