<?php

declare(strict_types=1);

use App\Models\Artwork;
use App\Models\User;
use Illuminate\Support\Facades\DB;

beforeEach(function () {
    // Use null Scout driver so no Meilisearch calls are made
    config(['scout.driver' => 'null']);
});

it('redirects unauthenticated users to login', function () {
    $this->get(route('discover.following'))
        ->assertRedirect(route('login'));
});

it('shows empty state with fallback data when user follows nobody', function () {
    $user = User::factory()->create();

    $response = $this->actingAs($user)->get(route('discover.following'));

    $response->assertStatus(200);
    $response->assertViewHas('empty', true);
    $response->assertViewHas('fallback_trending');
    $response->assertViewHas('fallback_creators');
    $response->assertViewHas('section', 'following');
});

it('paginates artworks from followed creators', function () {
    $user    = User::factory()->create();
    $creator = User::factory()->create();

    // user_followers has no updated_at column
    DB::table('user_followers')->insert([
        'user_id'     => $creator->id,
        'follower_id' => $user->id,
        'created_at'  => now(),
    ]);

    Artwork::factory()->count(3)->create([
        'user_id'      => $creator->id,
        'is_public'    => true,
        'is_approved'  => true,
        'published_at' => now()->subHour(),
    ]);

    $response = $this->actingAs($user)->get(route('discover.following'));

    $response->assertStatus(200);
    $response->assertViewHas('section', 'following');
    $response->assertViewMissing('empty');
});

it('does not include artworks from non-followed creators in the feed', function () {
    $user     = User::factory()->create();
    $creator  = User::factory()->create();
    $stranger = User::factory()->create();

    DB::table('user_followers')->insert([
        'user_id'     => $creator->id,
        'follower_id' => $user->id,
        'created_at'  => now(),
    ]);

    // Only the stranger has an artwork — creator has none
    Artwork::factory()->create([
        'user_id'      => $stranger->id,
        'is_public'    => true,
        'is_approved'  => true,
        'published_at' => now()->subHour(),
    ]);

    $response = $this->actingAs($user)->get(route('discover.following'));
    $response->assertStatus(200);

    /** @var \Illuminate\Pagination\LengthAwarePaginator $artworks */
    $artworks = $response->original->gatherData()['artworks'];
    expect($artworks->total())->toBe(0);
});

it('other discover routes return 200 without Meilisearch', function () {
    // Trending and fresh routes fall through to DB fallback with null driver
    $this->get(route('discover.trending'))->assertStatus(200);
    $this->get(route('discover.fresh'))->assertStatus(200);
});
