<?php

namespace Tests\Feature;

use Illuminate\Foundation\Testing\RefreshDatabase;

use Tests\TestCase;

use App\Models\Page;
use App\Models\PageRevision;

class PageRenderTest extends TestCase
{
    use RefreshDatabase;

    public function test_page_render_view() {
        $page = Page::factory()->create([
            'is_published' => true,
            'main' => false,
            'visibility' => 'public',
        ]);

        PageRevision::factory()->create([
            'page_id' => $page->id,
            'user_id' => $page->user_id,
            'active' => true,
            'content' => json_encode(['blocks' => []]),
            'label' => 'published',
        ]);

        $response = $this->get('/p/' . $page->slug);

        $response->assertStatus(200);
        $response->assertInertia(fn ($page) => $page->component('Root'));
    }

    public function test_main_page_returns_404_if_viewed_with_slug() {
        $page = Page::factory()->create([
            'is_published' => true,
            'main' => true,
            'visibility' => 'public',
        ]);

        PageRevision::factory()->create([
            'page_id' => $page->id,
            'user_id' => $page->user_id,
            'active' => true,
            'content' => json_encode(['blocks' => []]),
            'label' => 'published',
        ]);

        $response = $this->get('/p/' . $page->slug);
        $response->assertStatus(404);
    }

    public function test_unpublished_page_returns_403() {
        $page = Page::factory()->create([
            'is_published' => false,
            'main' => false,
            'visibility' => 'public',
        ]);

        PageRevision::factory()->create([
            'page_id' => $page->id,
            'user_id' => $page->user_id,
            'active' => true,
            'content' => json_encode(['blocks' => []]),
            'label' => 'manual-save',
        ]);

        $response = $this->get('/p/' . $page->slug);
        $response->assertStatus(403);
    }

    public function test_private_page_redirects_for_guests() {
        $page = Page::factory()->create([
            'is_published' => true,
            'main' => false,
            'visibility' => 'private',
        ]);

        PageRevision::factory()->create([
            'page_id' => $page->id,
            'user_id' => $page->user_id,
            'active' => true,
            'content' => json_encode(['blocks' => []]),
            'label' => 'published',
        ]);

        $response = $this->get('/p/' . $page->slug);
        $response->assertStatus(403);
    }
}
