<?php

namespace Tests\Feature;

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

/**
 * clusev:install (install.sh phase 8) — first-admin bootstrap. The operator chose a known
 * default password ('clusev') for predictable login; must_change_password forces a new one
 * on first login, which is what keeps the default acceptable.
 */
class InstallCommandTest extends TestCase
{
    use RefreshDatabase;

    public function test_creates_admin_with_default_password_and_forced_change(): void
    {
        $this->artisan('clusev:install', ['--email' => 'admin@example.test'])->assertSuccessful();

        $user = User::where('email', 'admin@example.test')->first();
        $this->assertNotNull($user);
        $this->assertTrue(Hash::check('clusev', $user->password), 'admin password must be the default "clusev"');
        $this->assertTrue((bool) $user->must_change_password, 'first login must be forced to change it');
    }

    public function test_uses_the_fixed_default_email_when_none_is_given(): void
    {
        $this->artisan('clusev:install')->assertSuccessful();

        $user = User::sole();
        $this->assertSame('admin@clusev.local', $user->email, 'a fresh install must default to the predictable admin@clusev.local');
        $this->assertTrue(Hash::check('clusev', $user->password));
        $this->assertTrue((bool) $user->must_change_password);
    }

    public function test_is_a_noop_when_an_admin_already_exists(): void
    {
        User::factory()->create();

        $this->artisan('clusev:install', ['--email' => 'second@example.test'])->assertSuccessful();

        $this->assertSame(1, User::count());
        $this->assertNull(User::where('email', 'second@example.test')->first());
    }
}
