<?php

use App\Models\Group;
use App\Models\User;
use Database\Seeders\MenuSeeder;

use function Pest\Laravel\actingAs;

function adminUser(): User
{
    $admin = User::factory()->create();
    $admin->groups()->attach(Group::firstOrCreate(['name' => Group::ADMIN]));

    return $admin->fresh();
}

function memberUser(): User
{
    $member = User::factory()->create();
    $member->groups()->attach(Group::firstOrCreate(['name' => Group::MEMBERS]));

    return $member->fresh();
}

beforeEach(function () {
    Group::firstOrCreate(['name' => Group::ADMIN]);
    Group::firstOrCreate(['name' => Group::MEMBERS]);
});

test('admin can view users index', function () {
    actingAs(adminUser())
        ->get(route('users.index'))
        ->assertOk();
});

test('member is redirected away from users index', function () {
    actingAs(memberUser())
        ->get(route('users.index'))
        ->assertRedirect(route('dashboard'));
});

test('admin can create a user with a group', function () {
    $response = actingAs(adminUser())->post(route('users.store'), [
        'name' => 'New User',
        'email' => 'new@example.com',
        'password' => 'secret123',
        'credit' => 500,
        'active' => true,
        'groups' => [Group::MEMBERS],
    ]);

    $response->assertRedirect(route('users.index'));

    $user = User::where('email', 'new@example.com')->first();
    expect($user)->not->toBeNull()
        ->and($user->credit)->toBe(500)
        ->and($user->groupNames()->contains(Group::MEMBERS))->toBeTrue();
});

test('admin can update a user and sync groups', function () {
    $admin = adminUser();
    $target = memberUser();

    actingAs($admin)
        ->put(route('users.update', $target), [
            'name' => 'Updated Name',
            'email' => 'updated@example.com',
            'credit' => 1000,
            'active' => true,
            'groups' => [Group::ADMIN],
        ])
        ->assertRedirect(route('users.index'));

    $target->refresh();
    expect($target->name)->toBe('Updated Name')
        ->and($target->credit)->toBe(1000)
        ->and($target->groupNames()->contains(Group::ADMIN))->toBeTrue()
        ->and($target->groupNames()->contains(Group::MEMBERS))->toBeFalse();
});

test('group management page shows groups with member counts', function () {
    actingAs(adminUser())
        ->get(route('groups.index'))
        ->assertOk();
});

test('dynamic nav is filtered by user group', function () {
    // Nav sekarang DB-driven — seed satu menu agar nav tidak kosong.
    $this->seed(MenuSeeder::class);

    $response = actingAs(adminUser())->get(route('dashboard'));
    $response->assertOk();

    // Admin should see the nav prop with sections.
    $nav = $response->inertiaProps()['nav'];
    expect($nav)->toBeArray()->not->toBeEmpty();
});
