<?php

use MintyPHP\Buffer;
use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Repository\Access\RoleRepository;
use MintyPHP\Router;
use MintyPHP\Service\Access\PermissionAuthorizationPolicy;
use MintyPHP\Support\Flash;
use MintyPHP\Support\Guard;

$session = app(SessionStoreInterface::class)->all();
Guard::requireLogin();
$request = requestInput();
$returnTarget = requestResolveReturnTarget();
$closeTarget = requestResolveReturnTarget('admin/permissions');

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

// Resolve the permission BEFORE the aggregator so the authorize-context can
// carry the real target_permission_id + target_is_system flag (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 find() returned null.
$permission = $id > 0 ? app(\MintyPHP\Service\Access\PermissionService::class)->find($id) : null;
$isSystemPermission = (int) ($permission['is_system'] ?? 0) === 1;

$context = actionEditContext([
    'finder' => static fn (string $_id): mixed => $permission,
    'rawId' => (string) $id,
    'notFoundFlashKey' => 'Permission not found',
    'notFoundRedirectPath' => $closeTarget,
    'notFoundFlashScopeKey' => 'permission_not_found',
    'abilityKey' => PermissionAuthorizationPolicy::ABILITY_ADMIN_PERMISSIONS_EDIT_CONTEXT,
    'context' => [
        'actor_user_id' => $currentUserId,
        'target_permission_id' => $id,
        'target_is_system' => $isSystemPermission,
    ],
    'viewAuthFlags' => ['can_update_permission', 'can_delete_permission'],
    'forbiddenStrategy' => 'deny',
]);
$permission = is_array($context['model']) ? $context['model'] : $permission;
$capabilities = $context['capabilities'];
$tenantScope = $context['tenantScope'];
$viewAuth = $context['viewAuth'];
$canUpdatePermission = (bool) ($capabilities['can_update_permission'] ?? false);
$canDeletePermission = (bool) ($capabilities['can_delete_permission'] ?? false);
// Permissions-Edit konsumiert $tenantScope['ids'] bewusst NICHT — Permissions
// sind global, kein Filter-Szenario. $canManageAllPermissions bleibt als Hook
// fuer kuenftige Policy-Erweiterungen definiert.
$canManageAllPermissions = $tenantScope['scope'] === 'all';

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

$errorBag = formErrors();
$errors = [];
$form = $permission;
$roles = app(RoleRepository::class)->listActive();
$selectedRoleIds = $rolePermissionRepository->listRoleIdsByPermissionId($id);
$previousRoleIds = $selectedRoleIds;

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

if ($request->isMethod('POST')) {
    $submitDecision = $authorizationService->authorize(PermissionAuthorizationPolicy::ABILITY_ADMIN_PERMISSIONS_EDIT_SUBMIT, [
        'actor_user_id' => $currentUserId,
        'target_permission_id' => $id,
        'target_is_system' => $isSystemPermission,
    ]);
    if (!$submitDecision->isAllowed()) {
        Guard::deny();
    }
    $result = app(\MintyPHP\Service\Access\PermissionService::class)->updateFromAdmin($id, $request->bodyAll());
    $form = $result['form'] ?? $form;
    $errorBag->merge($result['errors'] ?? []);
    $selectedRoleIds = toIntIds($request->body('role_ids', $selectedRoleIds));

    if (($result['ok'] ?? false) && !$errorBag->hasAny()) {
        $roleIds = toIntIds($request->body('role_ids', []));
        $syncSucceeded = false;
        $dbSession = app(\MintyPHP\Repository\Support\DatabaseSessionRepository::class);
        $dbSession->beginTransaction();
        try {
            $rolePermissionRepository->replaceForPermission($id, $roleIds);
            $affectedRoleIds = array_values(array_unique(array_merge($previousRoleIds, $roleIds)));
            $affectedUserIds = $userRoleRepository->listUserIdsByRoleIds($affectedRoleIds);
            if ($affectedUserIds) {
                $userWriteRepository->bumpAuthzVersionByUserIds($affectedUserIds);
            }
            $dbSession->commitTransaction();
            $syncSucceeded = true;
        } catch (\Throwable) {
            try {
                $dbSession->rollbackTransaction();
            } catch (\Throwable) {
            }
            $errorBag->merge([t('Failed to update permission roles')]);
        }
        if ($syncSucceeded) {
            $action = (string) $request->body('action', 'save');
            if ($action === 'save_close') {
                Flash::success(t('Permission updated'), $closeTarget, 'permission_updated');
                Router::redirect($closeTarget);
            } else {
                Flash::success(t('Permission updated'), $editTarget, 'permission_updated');
                Router::redirect($editTarget);
            }
        }
    }
}

$validationSummaryErrors = $errorBag->toArray();
$errors = $errorBag->toFlatList();
$titleText = $canUpdatePermission ? t('Edit permission') : t('View permission');
Buffer::set('title', $titleText);
$breadcrumbs = [
    ['label' => t('Home'), 'path' => 'admin'],
    ['label' => t('Permissions'), 'path' => 'admin/permissions'],
    ['label' => $titleText],
];
