<?php

declare(strict_types=1);

use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;

uses(RefreshDatabase::class);

it('admin can inspect feed engine decisions for a user bucket', function () {
    config()->set('discovery.v2.enabled', true);
    config()->set('discovery.v2.rollout_percentage', 35);
    config()->set('discovery.v2.algo_version', 'clip-cosine-v2-adaptive');

    $admin = User::factory()->create(['role' => 'admin']);
    $subject = User::factory()->create();
    $expectedBucket = abs((int) crc32((string) $subject->id)) % 100;

    $response = $this->actingAs($admin)
        ->getJson('/api/admin/reports/feed-engine-decision?user_id=' . $subject->id);

    $response->assertOk();
    $response->assertJsonPath('decision.user_id', $subject->id);
    $response->assertJsonPath('decision.bucket', $expectedBucket);
    $response->assertJsonPath('decision.rollout_percentage', 35);
    $response->assertJsonPath('decision.uses_v2', $expectedBucket < 35);
    $response->assertJsonPath('decision.selected_engine', $expectedBucket < 35 ? 'v2' : 'v1');
});

it('admin can inspect explicit v2 algo overrides even when rollout is disabled', function () {
    config()->set('discovery.v2.enabled', false);
    config()->set('discovery.v2.rollout_percentage', 0);
    config()->set('discovery.v2.algo_version', 'clip-cosine-v2-adaptive');

    $admin = User::factory()->create(['role' => 'admin']);
    $subject = User::factory()->create();

    $response = $this->actingAs($admin)
        ->getJson('/api/admin/reports/feed-engine-decision?user_id=' . $subject->id . '&algo_version=clip-cosine-v2-adaptive');

    $response->assertOk();
    $response->assertJsonPath('decision.uses_v2', true);
    $response->assertJsonPath('decision.selected_engine', 'v2');
    $response->assertJsonPath('decision.reason', 'explicit_algo_override');
});

it('non-admin is denied feed engine decision endpoint', function () {
    $user = User::factory()->create(['role' => 'user']);
    $subject = User::factory()->create();

    $response = $this->actingAs($user)
        ->getJson('/api/admin/reports/feed-engine-decision?user_id=' . $subject->id);

    $response->assertStatus(403);
});
