<?php

require_once __DIR__ . '/../../autoload/Controllers/UsersController.php';

use Controllers\UsersController;

function assert_users_controller_same( $expected, $actual, $message )
{
  if ( $expected !== $actual )
    throw new Exception( $message );
}

function run_users_controller_tests()
{
  $admin_user = [ 'id' => 1, 'name' => 'Admin', 'surname' => 'One' ];
  $regular_user = [ 'id' => 3, 'name' => 'Jan', 'surname' => 'Kowalski' ];
  $target_user = [ 'id' => 5, 'name' => 'Anna', 'surname' => 'Nowak' ];

  assert_users_controller_same( true, UsersController::canManageUsers( $admin_user, null ), 'Expected admin to manage users.' );
  assert_users_controller_same( false, UsersController::canManageUsers( $regular_user, null ), 'Expected regular user to not manage users.' );
  assert_users_controller_same( true, UsersController::canManageUsers( $regular_user, $admin_user ), 'Expected impersonated admin session to manage users.' );

  $state = UsersController::impersonationStateAfterLoginAs( $admin_user, $target_user, null );
  assert_users_controller_same( 5, (int)$state['user']['id'], 'Expected impersonation to switch current user to target user.' );
  assert_users_controller_same( 1, (int)$state['impersonator_user']['id'], 'Expected impersonator to be preserved as admin user.' );

  $state_with_existing = UsersController::impersonationStateAfterLoginAs( $regular_user, $target_user, $admin_user );
  assert_users_controller_same( 1, (int)$state_with_existing['impersonator_user']['id'], 'Expected existing impersonator to stay unchanged.' );

  $view_model = UsersController::buildMainViewModel( $target_user, $admin_user, [ $admin_user, $regular_user, $target_user ], [] );
  assert_users_controller_same( true, $view_model['can_switch_back'], 'Expected can_switch_back to be true when impersonator is admin.' );
}
