<?php

use MintyPHP\Buffer;
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();
$request = requestInput();
$returnTarget = requestResolveReturnTarget();
$closeTarget = requestResolveReturnTarget('admin/roles');

$currentUserId = (int) ($session['user']['id'] ?? 0);
$uuid = trim((string) ($id ?? ''));
$editTarget = requestPathWithReturnTarget("admin/roles/edit/{$uuid}", $returnTarget);

// Resolve the role BEFORE the aggregator so the authorize-context can carry
// the real target_role_id (matches today's order: lookup → CONTEXT authorize
// → Guard::deny()). The aggregator receives a trivial finder that returns the
// already-loaded model so its not-found branch fires only when findByUuid
// returned null.
$role = $uuid !== '' ? app(\MintyPHP\Service\Access\RoleService::class)->findByUuid($uuid) : null;
$roleId = (int) ($role['id'] ?? 0);

$context = actionEditContext([
    'finder' => static fn (string $_id): mixed => $role,
    'rawId' => $uuid,
    'notFoundFlashKey' => 'Role not found',
    'notFoundRedirectPath' => $closeTarget,
    'notFoundFlashScopeKey' => 'role_not_found',
    'abilityKey' => RoleAuthorizationPolicy::ABILITY_ADMIN_ROLES_EDIT_CONTEXT,
    'context' => [
        'actor_user_id' => $currentUserId,
        'target_role_id' => $roleId,
    ],
    'viewAuthFlags' => ['can_edit_role', 'can_delete_role'],
    'forbiddenStrategy' => 'deny',
]);
$role = is_array($context['model']) ? $context['model'] : $role;
$capabilities = $context['capabilities'];
$tenantScope = $context['tenantScope'];
$viewAuth = $context['viewAuth'];
$canUpdateRole = (bool) ($capabilities['can_edit_role'] ?? false);
$canDeleteRole = (bool) ($capabilities['can_delete_role'] ?? false);
// Roles-Edit konsumiert $tenantScope['ids'] bewusst NICHT — Roles sind global,
// kein Filter-Szenario. $canManageAllRoles bleibt als Hook fuer kuenftige
// Policy-Erweiterungen definiert.
$canManageAllRoles = $tenantScope['scope'] === 'all';

$authorizationService = app(\MintyPHP\Service\Access\AuthorizationService::class);
$permissionRepository = app(\MintyPHP\Repository\Access\PermissionRepository::class);
$rolePermissionRepository = app(\MintyPHP\Repository\Access\RolePermissionRepository::class);
$userRoleRepository = app(\MintyPHP\Repository\Access\UserRoleRepository::class);
$userWriteRepository = app(\MintyPHP\Repository\User\UserWriteRepository::class);

app(\MintyPHP\Service\Audit\AuditMetadataEnricherInterface::class)->enrich($role);

$errorBag = formErrors();
$errors = [];
$warnings = [];
$form = $role;
$permissions = $permissionRepository->listActive();
$selectedPermissionIds = $rolePermissionRepository->listPermissionIdsByRoleId($roleId);
$assignableRoleService = app(\MintyPHP\Service\Access\AssignableRoleService::class);
$assignableRoleRepo = app(\MintyPHP\Repository\Access\RoleAssignableRoleRepository::class);
$allRolesForAssignable = app(\MintyPHP\Service\Access\RoleService::class)->listActive();
$selectedAssignableRoleIds = $assignableRoleRepo->listAssignableRoleIdsByRoleId($roleId);

if ($request->isMethod('POST') && !actionRequireCsrf($editTarget, $editTarget, 'csrf_expired')) {
    return;
}

if ($request->isMethod('POST')) {
    $submitDecision = $authorizationService->authorize(RoleAuthorizationPolicy::ABILITY_ADMIN_ROLES_EDIT_SUBMIT, [
        'actor_user_id' => $currentUserId,
        'target_role_id' => $roleId,
    ]);
    if (!$submitDecision->isAllowed()) {
        Guard::deny();
    }
    $result = app(\MintyPHP\Service\Access\RoleService::class)->updateFromAdmin($roleId, $request->bodyAll(), $currentUserId);
    $form = $result['form'] ?? $form;
    $warnings = $result['warnings'] ?? [];
    $errorBag->merge($result['errors'] ?? []);
    $selectedPermissionIds = toIntIds($request->body('permission_ids', $selectedPermissionIds));
    $selectedAssignableRoleIds = toIntIds($request->body('assignable_role_ids', $selectedAssignableRoleIds));

    if (($result['ok'] ?? false) && !$errorBag->hasAny()) {
        $permissionIds = toIntIds($request->body('permission_ids', []));
        $syncSucceeded = false;
        $dbSession = app(\MintyPHP\Repository\Support\DatabaseSessionRepository::class);
        $dbSession->beginTransaction();
        try {
            $rolePermissionRepository->replaceForRole($roleId, $permissionIds);
            $assignableRoleService->replaceAssignableRoles($roleId, $selectedAssignableRoleIds, $currentUserId);
            $affectedUserIds = $userRoleRepository->listUserIdsByRoleIds([$roleId]);
            if ($affectedUserIds) {
                $userWriteRepository->bumpAuthzVersionByUserIds($affectedUserIds);
            }
            $dbSession->commitTransaction();
            $syncSucceeded = true;
        } catch (\Throwable) {
            try {
                $dbSession->rollbackTransaction();
            } catch (\Throwable) {
            }
            $errorBag->merge([t('Failed to update role permissions')]);
        }
        if ($syncSucceeded) {
            $action = (string) $request->body('action', 'save');
            if ($action === 'save_close') {
                if ($warnings) {
                    Flash::info(implode(' ', $warnings), $closeTarget, 'role_warning');
                }
                Flash::success(t('Role updated'), $closeTarget, 'role_updated');
                Router::redirect($closeTarget);
            } else {
                if ($warnings) {
                    Flash::info(implode(' ', $warnings), $editTarget, 'role_warning');
                }
                Flash::success(t('Role updated'), $editTarget, 'role_updated');
                Router::redirect($editTarget);
            }
        }
    }
}

$validationSummaryErrors = $errorBag->toArray();
$errors = $errorBag->toFlatList();
$titleText = $canUpdateRole ? t('Edit role') : t('View role');
Buffer::set('title', $titleText);
$breadcrumbs = [
    ['label' => t('Home'), 'path' => 'admin'],
    ['label' => t('Roles'), 'path' => 'admin/roles'],
    ['label' => $titleText],
];
