<?php

namespace Tests\Feature\Role;

use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class RolesTest extends TestCase
{
    use RefreshDatabase;

    protected function loginAsManager()
    {
        $user = User::factory()->create([
            'email' => 'manager@example.com',
            'password' => bcrypt('password123'),
            'role' => 'manager',
            'active' => true,
        ]);

        $response = $this->postJson('/api/auth/login', [
            'email' => 'manager@example.com',
            'password' => 'password123',
        ]);

        return $response->json('access_token');
    }

    /** @test */
    public function roles_endpoint_returns_list_of_roles()
    {
        $token = $this->loginAsManager();
        $this->seed(\Database\Seeders\RoleSeeder::class);

        $response = $this->withToken($token)->getJson('/api/roles');

        $response->assertOk();
        $response->assertJsonStructure([
            'data' => [
                '*' => ['id', 'name', 'description'],
            ],
        ]);
        $response->assertJsonCount(7, 'data'); // 7 roles from seeder
    }

    /** @test */
    public function roles_are_ordered_by_name()
    {
        $token = $this->loginAsManager();
        $this->seed(\Database\Seeders\RoleSeeder::class);

        $response = $this->withToken($token)->getJson('/api/roles');

        $response->assertOk();
        $roles = $response->json('data');
        $names = array_column($roles, 'name');
        $sortedNames = $names;
        sort($sortedNames);
        $this->assertEquals($sortedNames, $names);
    }

    /** @test */
    public function roles_endpoint_requires_authentication()
    {
        $response = $this->getJson('/api/roles');

        $response->assertUnauthorized();
    }
}
