<?php

namespace Tests\Feature;

use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Hash;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;
use Tests\TestCase;

class InstallApplicationCommandTest extends TestCase
{
    use RefreshDatabase;

    public function test_install_command_bootstraps_default_rbac_and_admin_user(): void
    {
        $this->artisan('app:install')
            ->assertExitCode(0);

        $this->assertDatabaseHas('permissions', [
            'name' => 'platform.users.manage',
            'guard_name' => 'api',
        ]);
        $this->assertDatabaseHas('roles', [
            'name' => 'admin',
            'guard_name' => 'api',
        ]);
        $this->assertDatabaseHas('users', [
            'email' => 'admin@example.com',
            'nickname' => 'admin',
        ]);

        $adminUser = User::query()->where('email', 'admin@example.com')->first();
        $this->assertNotNull($adminUser);
        $this->assertTrue(Hash::check('admin', (string) $adminUser->password));
        $this->assertTrue($adminUser->hasRole('admin', 'api'));

        $adminRole = Role::query()->where('name', 'admin')->where('guard_name', 'api')->first();
        $this->assertNotNull($adminRole);
        $this->assertSame(
            Permission::query()->where('guard_name', 'api')->count(),
            $adminRole->permissions()->count()
        );
    }
}
