<?php

declare(strict_types=1);

use App\Models\User;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Tests\TestCase;

uses(TestCase::class);

beforeEach(function (): void {
    Schema::dropIfExists('tag_interaction_daily_metrics');
    Schema::dropIfExists('tags');
    Schema::dropIfExists('users');

    Schema::create('users', function (Blueprint $table): void {
        $table->id();
        $table->string('username')->nullable();
        $table->timestamp('username_changed_at')->nullable();
        $table->timestamp('last_username_change_at')->nullable();
        $table->string('onboarding_step')->nullable();
        $table->string('name')->nullable();
        $table->string('email')->nullable();
        $table->timestamp('email_verified_at')->nullable();
        $table->string('password')->nullable();
        $table->boolean('is_active')->default(true);
        $table->string('role')->nullable();
        $table->rememberToken();
        $table->timestamps();
        $table->softDeletes();
    });

    Schema::create('tags', function (Blueprint $table): void {
        $table->id();
        $table->string('name');
        $table->string('slug')->unique();
        $table->unsignedInteger('usage_count')->default(0);
        $table->boolean('is_active')->default(true);
        $table->timestamps();
    });

    Schema::create('tag_interaction_daily_metrics', function (Blueprint $table): void {
        $table->id();
        $table->date('metric_date');
        $table->string('surface', 32);
        $table->string('tag_slug', 120)->default('');
        $table->string('source_tag_slug', 120)->default('');
        $table->string('query', 120)->default('');
        $table->unsignedInteger('clicks')->default(0);
        $table->unsignedInteger('unique_users')->default(0);
        $table->unsignedInteger('unique_sessions')->default(0);
        $table->decimal('avg_position', 8, 2)->default(0);
        $table->timestamps();
    });
});

it('redirects guests away from the studio tag search route', function (): void {
    $this->get('/api/studio/tags/search?q=hi')
        ->assertRedirect('/login');
});

it('returns momentum-ranked tag suggestions for authenticated studio users', function (): void {
    $now = now();

    $user = new User([
        'username' => 'studio-user',
        'username_changed_at' => now()->subDays(120),
        'last_username_change_at' => now()->subDays(120),
        'onboarding_step' => 'complete',
        'name' => 'Studio User',
        'email' => 'studio@example.com',
        'email_verified_at' => now(),
        'password' => 'password',
        'is_active' => true,
    ]);
    $user->id = 1;

    DB::table('tags')->insert([
        ['id' => 1, 'name' => 'High Usage', 'slug' => 'high-usage', 'usage_count' => 500, 'is_active' => true, 'created_at' => $now, 'updated_at' => $now],
        ['id' => 2, 'name' => 'High Contrast', 'slug' => 'high-contrast', 'usage_count' => 120, 'is_active' => true, 'created_at' => $now, 'updated_at' => $now],
        ['id' => 3, 'name' => 'Hidden Draft', 'slug' => 'hidden-draft', 'usage_count' => 900, 'is_active' => false, 'created_at' => $now, 'updated_at' => $now],
    ]);

    DB::table('tag_interaction_daily_metrics')->insert([
        [
            'metric_date' => $now->toDateString(),
            'surface' => 'tag_search',
            'tag_slug' => 'high-contrast',
            'source_tag_slug' => '',
            'query' => 'hi',
            'clicks' => 30,
            'unique_users' => 0,
            'unique_sessions' => 11,
            'avg_position' => 1.1,
            'created_at' => $now,
            'updated_at' => $now,
        ],
        [
            'metric_date' => $now->toDateString(),
            'surface' => 'tag_search',
            'tag_slug' => 'high-usage',
            'source_tag_slug' => '',
            'query' => 'hi',
            'clicks' => 3,
            'unique_users' => 0,
            'unique_sessions' => 2,
            'avg_position' => 2.8,
            'created_at' => $now,
            'updated_at' => $now,
        ],
    ]);

    $response = $this->actingAs($user)->getJson('/api/studio/tags/search?q=hi');

    $response->assertOk();

    $data = $response->json();

    expect($data)->toHaveCount(2);
    expect(array_column($data, 'slug'))->toBe(['high-contrast', 'high-usage']);
    expect((int) $data[0]['recent_clicks'])->toBe(30);
    expect($data[0])->toHaveKeys(['id', 'name', 'slug', 'usage_count', 'recent_clicks']);
    expect($data[0])->not->toHaveKeys(['created_at', 'updated_at', 'is_active']);
});