<?php

use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Router;
use MintyPHP\Service\Access\RoleAuthorizationPolicy;
use MintyPHP\Support\Flash;
use MintyPHP\Support\Guard;

$session = app(SessionStoreInterface::class)->all();
Guard::requireLogin();

$currentUserId = (int) ($session['user']['id'] ?? 0);
$authorizationService = app(\MintyPHP\Service\Access\AuthorizationService::class);
$decision = $authorizationService->authorize(RoleAuthorizationPolicy::ABILITY_ADMIN_ROLES_DELETE, [
    'actor_user_id' => $currentUserId,
]);
if (!$decision->isAllowed()) {
    Guard::deny();
}

$uuid = trim((string) ($id ?? ''));
if ($uuid === '') {
    Router::redirect('admin/roles');
    return;
}

$role = app(\MintyPHP\Service\Access\RoleService::class)->findByUuid($uuid);
$affectedUserIds = [];
if ($role) {
    $roleId = (int) ($role['id'] ?? 0);
    if ($roleId > 0) {
        $affectedUserIds = app(\MintyPHP\Repository\Access\UserRoleRepository::class)->listUserIdsByRoleIds([$roleId]);
    }
}

$result = app(\MintyPHP\Service\Access\RoleService::class)->deleteByUuid($uuid);
if (!($result['ok'] ?? false)) {
    $error = $result['error'] ?? 'unknown';
    if ($error === 'admin_role_protected') {
        Flash::error('The Admin role cannot be deleted', 'admin/roles', 'admin_role_protected');
    } else {
        Flash::error('Role not found', 'admin/roles', 'role_not_found');
    }
    Router::redirect('admin/roles');
}

if ($affectedUserIds) {
    app(\MintyPHP\Repository\User\UserWriteRepository::class)->bumpAuthzVersionByUserIds($affectedUserIds);
}

Flash::success('Role deleted', 'admin/roles', 'role_deleted');
Router::redirect('admin/roles');
