<?php

namespace Tests\Feature\Api;

use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Cache;
use Laravel\Sanctum\Sanctum;
use Tests\TestCase;

class HelpControllerTest extends TestCase
{
    use RefreshDatabase;

    protected function setUp(): void
    {
        parent::setUp();

        Cache::put('help.guest.en', collect([
            [
                'slug' => 'getting-started',
                'title' => 'Getting Started',
                'summary' => 'Welcome guide',
                'body_html' => '<p>When to read this</p>',
            ],
        ]), now()->addMinutes(30));

        Cache::put('help.admin.en', collect([
            [
                'slug' => 'tenant-dashboard-overview',
                'title' => 'Dashboard Overview',
                'summary' => 'Overview for admins',
                'body_html' => '<p>Admin guide</p>',
            ],
        ]), now()->addMinutes(30));
    }

    public function test_guest_help_listing_is_public(): void
    {
        $response = $this->getJson('/api/v1/help?audience=guest&locale=en');

        $response->assertOk()
            ->assertJsonStructure(['data' => [['slug', 'title', 'summary']]])
            ->assertJsonFragment(['slug' => 'getting-started']);
    }

    public function test_guest_help_detail_returns_article(): void
    {
        $response = $this->getJson('/api/v1/help/getting-started?audience=guest&locale=en');

        $response->assertOk()
            ->assertJsonPath('data.slug', 'getting-started');

        $this->assertStringContainsString('When to read this', $response->json('data.body_html'));
    }

    public function test_admin_help_requires_authentication(): void
    {
        $this->getJson('/api/v1/help?audience=admin&locale=en')->assertStatus(401);
    }

    public function test_admin_help_allows_authenticated_users(): void
    {
        $user = User::factory()->create([
            'role' => 'tenant_admin',
        ]);

        Sanctum::actingAs($user);

        $response = $this->getJson('/api/v1/help?audience=admin&locale=en');

        $response->assertOk()
            ->assertJsonFragment(['slug' => 'tenant-dashboard-overview']);
    }
}
