<?php

namespace Tests\Feature;

use App\Models\Gallery;
use Carbon\Carbon;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Hash;
use Tests\TestCase;

class GalleryAccessTest extends TestCase
{
    use DatabaseTransactions;

    protected function setUp(): void
    {
        parent::setUp();
        Artisan::call('migrate');
    }

    public function test_redirects_to_access_page_when_password_is_required(): void
    {
        $gallery = Gallery::factory()->create([
            'require_password' => true,
            'password_hash' => Hash::make('secret123'),
            'expires_at' => null,
            'access_duration_minutes' => null,
        ]);

        $response = $this->get(route('gallery.show', $gallery));
        $response->assertRedirect(route('gallery.access.show', $gallery));
    }

    public function test_allows_access_after_correct_password(): void
    {
        $gallery = Gallery::factory()->create([
            'require_password' => true,
            'password_hash' => Hash::make('secret123'),
            'expires_at' => null,
            'access_duration_minutes' => null,
        ]);

        $this->post(route('gallery.access.store', $gallery), ['password' => 'secret123'])
            ->assertRedirect(route('gallery.show', $gallery));

        $this->get(route('gallery.show', $gallery))->assertOk();
        $this->getJson('/api/images?gallery='.$gallery->slug)->assertOk();
    }

    public function test_denies_access_when_gallery_expired(): void
    {
        $gallery = Gallery::factory()->create([
            'expires_at' => Carbon::now()->subMinute(),
            'require_password' => false,
            'access_duration_minutes' => null,
            'password_hash' => null,
        ]);

        $this->get(route('gallery.show', $gallery))->assertRedirect(route('gallery.access.show', $gallery));
        $this->getJson('/api/images?gallery='.$gallery->slug)->assertForbidden();
    }
}
