<?php

declare(strict_types=1);

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

it('falls back to the latest 1000 downloads when today has no downloads', function () {
    $newerArtwork = Artwork::factory()->create([
        'title' => 'Latest Window Artwork',
        'published_at' => now()->subDays(5),
    ]);

    $olderArtwork = Artwork::factory()->create([
        'title' => 'Older Window Artwork',
        'published_at' => now()->subDays(5),
    ]);

    DB::table('artwork_downloads')->insert([
        [
            'artwork_id' => $newerArtwork->id,
            'user_id' => null,
            'ip' => inet_pton('127.0.0.1'),
            'user_agent' => 'Pest',
            'created_at' => now()->subDay()->setTime(12, 0, 0),
        ],
        [
            'artwork_id' => $newerArtwork->id,
            'user_id' => null,
            'ip' => inet_pton('127.0.0.1'),
            'user_agent' => 'Pest',
            'created_at' => now()->subDays(2)->setTime(12, 0, 0),
        ],
        [
            'artwork_id' => $olderArtwork->id,
            'user_id' => null,
            'ip' => inet_pton('127.0.0.1'),
            'user_agent' => 'Pest',
            'created_at' => now()->subDays(3)->setTime(12, 0, 0),
        ],
    ]);

    $this->get('/downloads/today')
        ->assertOk()
        ->assertSee('Latest Window Artwork', false)
        ->assertSee('Older Window Artwork', false)
        ->assertSee('Latest 1000 downloads', false)
        ->assertDontSee('No download activity is available yet.', false);
});

it('prefers real today downloads over the fallback window', function () {
    $todayArtwork = Artwork::factory()->create([
        'title' => 'Today Download Artwork',
        'published_at' => now()->subDays(5),
    ]);

    $fallbackArtwork = Artwork::factory()->create([
        'title' => 'Fallback Only Artwork',
        'published_at' => now()->subDays(5),
    ]);

    DB::table('artwork_downloads')->insert([
        [
            'artwork_id' => $todayArtwork->id,
            'user_id' => null,
            'ip' => inet_pton('127.0.0.1'),
            'user_agent' => 'Pest',
            'created_at' => now()->setTime(11, 0, 0),
        ],
        [
            'artwork_id' => $fallbackArtwork->id,
            'user_id' => null,
            'ip' => inet_pton('127.0.0.1'),
            'user_agent' => 'Pest',
            'created_at' => now()->subDays(2)->setTime(12, 0, 0),
        ],
    ]);

    $this->get('/downloads/today')
        ->assertOk()
        ->assertSee('Today Download Artwork', false)
        ->assertSee('Live today', false)
        ->assertDontSee('Fallback Only Artwork', false)
        ->assertDontSee('Latest 1000 downloads', false);
});