<?php

namespace Tests\Feature\Api;

use App\Models\User;
use App\Models\Category;
use Laravel\Passport\Passport;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Artisan;
use Tests\TestCase;

class CategoryApiTest extends TestCase
{
    use RefreshDatabase;

    protected $user;

    protected function setUp(): void
    {
        parent::setUp();
        $this->user = User::factory()->create();
    }

    public function test_authenticated_user_can_list_root_categories_by_default()
    {
        $root = Category::factory()->create(['parent_id' => null]);
        Category::factory()->create(['parent_id' => $root->id]); // Child

        Passport::actingAs($this->user);

        $response = $this->getJson('/api/categories');

        $response->assertStatus(200)
                 ->assertJsonCount(1, 'data')
                 ->assertJsonPath('data.0.id', $root->id);
    }

    public function test_user_can_filter_categories_by_level()
    {
        $level1 = Category::factory()->create(['parent_id' => null, 'name' => 'Root']);
        $level2 = Category::factory()->create(['parent_id' => $level1->id, 'name' => 'Child']);

        Passport::actingAs($this->user);

        // Test level 1
        $response = $this->getJson('/api/categories?level=1');
        $response->assertStatus(200)
                 ->assertJsonCount(1, 'data')
                 ->assertJsonPath('data.0.name', 'Root');

        // Test level 2
        $response = $this->getJson('/api/categories?level=2');
        $response->assertStatus(200)
                 ->assertJsonCount(1, 'data')
                 ->assertJsonPath('data.0.name', 'Child');
    }

    public function test_user_can_filter_categories_by_parent_id()
    {
        $parent = Category::factory()->create();
        Category::factory()->count(3)->create(['parent_id' => $parent->id]);
        Category::factory()->count(2)->create(['parent_id' => null]);

        Passport::actingAs($this->user);

        $response = $this->getJson('/api/categories?parent_id=' . $parent->id);
        $response->assertStatus(200)
                 ->assertJsonCount(3, 'data');
    }

    public function test_unauthenticated_user_cannot_access_categories()
    {
        $response = $this->getJson('/api/categories');
        $response->assertStatus(401);
    }
}
