<?php

declare(strict_types=1);

use App\Models\Artwork;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Http;
use function Pest\Laravel\actingAs;
use function Pest\Laravel\postJson;

uses(RefreshDatabase::class);

it('returns normalized synchronous vision tag suggestions for the artwork owner', function (): void {
    config()->set('vision.enabled', true);
    config()->set('vision.gateway.base_url', 'https://vision.local');
    config()->set('cdn.files_url', 'https://files.local');

    $user = User::factory()->create();
    $artwork = Artwork::factory()->create([
        'user_id' => $user->id,
        'hash' => 'aabbcc112233',
    ]);

    Http::fake([
        'https://vision.local/analyze/all' => Http::response([
            'clip' => [
                ['tag' => 'Neon City', 'confidence' => 0.91],
                ['tag' => 'Night Sky', 'confidence' => 0.77],
            ],
            'yolo' => [
                ['label' => 'car', 'confidence' => 0.65],
            ],
        ], 200),
    ]);

    actingAs($user);

    $response = postJson('/api/uploads/' . $artwork->id . '/vision-suggest?limit=10');

    $response->assertOk()
        ->assertJsonPath('vision_enabled', true)
        ->assertJsonPath('source', 'gateway_sync')
        ->assertJsonPath('tags.0.slug', 'neon-city')
        ->assertJsonPath('tags.0.source', 'clip')
        ->assertJsonPath('tags.1.slug', 'night-sky')
        ->assertJsonPath('tags.2.slug', 'car');
});

it('returns 404 when a non-owner requests upload vision suggestions', function (): void {
    config()->set('vision.enabled', true);
    config()->set('vision.gateway.base_url', 'https://vision.local');
    config()->set('cdn.files_url', 'https://files.local');

    $owner = User::factory()->create();
    $viewer = User::factory()->create();
    $artwork = Artwork::factory()->create([
        'user_id' => $owner->id,
        'hash' => 'aabbcc112233',
    ]);

    actingAs($viewer);

    postJson('/api/uploads/' . $artwork->id . '/vision-suggest')
        ->assertStatus(404);
});

it('returns disabled payload when vision suggestions are turned off', function (): void {
    config()->set('vision.enabled', false);

    $user = User::factory()->create();
    $artwork = Artwork::factory()->create([
        'user_id' => $user->id,
    ]);

    actingAs($user);

    postJson('/api/uploads/' . $artwork->id . '/vision-suggest')
        ->assertOk()
        ->assertJsonPath('vision_enabled', false)
        ->assertJsonPath('tags', []);
});