<?php

use App\Models\User;
use App\Models\Role;
use App\Enums\UserType;
use App\Constants\Permissions;
use function Pest\Laravel\{actingAs, patch, delete, put};

beforeEach(function () {
    $this->superAdmin = User::factory()->create(['type' => UserType::SUPER_ADMIN, 'status' => 'active']);
    $this->otherSuperAdmin = User::factory()->create(['type' => UserType::SUPER_ADMIN, 'status' => 'active']);
    $this->admin = User::factory()->create(['type' => UserType::ADMIN, 'status' => 'active']);

    // Give admin permissions
    $role = Role::create(['name' => 'Admin Role ' . uniqid()]);
    $this->admin->roles()->attach($role);

    // Check if permission already exists before creating
    $permission = \App\Models\Permission::firstOrCreate(['name' => Permissions::MEMBER_DIRECTORY]);
    $role->permissions()->attach($permission);
});

test('super admin cannot be deleted', function () {
    actingAs($this->superAdmin)
        ->delete(route('admin.users.destroy', $this->otherSuperAdmin))
        ->assertSessionHas('error', 'Super Admin accounts cannot be deleted.');

    expect(User::find($this->otherSuperAdmin->id))->not->toBeNull();
});

test('super admin status cannot be changed', function () {
    actingAs($this->superAdmin)
        ->patch(route('admin.users.status', $this->otherSuperAdmin), ['status' => 'inactive'])
        ->assertSessionHas('error', 'Super Admin status cannot be changed.');

    $this->otherSuperAdmin->refresh();
    expect($this->otherSuperAdmin->status)->toBe('active');
});

test('super admin role/type cannot be changed', function () {
    $newRole = Role::create(['name' => 'Employee Role ' . uniqid()]);

    actingAs($this->superAdmin)
        ->put(route('admin.users.update', $this->otherSuperAdmin), [
            'name' => 'Updated Name',
            'email' => $this->otherSuperAdmin->email,
            'role_id' => $newRole->id,
        ])
        ->assertSessionHas('error', 'Super Admin configuration cannot be changed.');

    $this->otherSuperAdmin->refresh();
    expect($this->otherSuperAdmin->type)->toBe(UserType::SUPER_ADMIN);
});
