<?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');
$createTarget = requestPathWithReturnTarget('admin/roles/create', $returnTarget);

$currentUserId = (int) ($session['user']['id'] ?? 0);

$context = actionCreateContext([
    'abilityKey' => RoleAuthorizationPolicy::ABILITY_ADMIN_ROLES_CREATE,
    'context' => ['actor_user_id' => $currentUserId],
    'viewAuthFlags' => [],
    'forbiddenStrategy' => 'deny',
]);
$capabilities = $context['capabilities'];
$tenantScope = $context['tenantScope'];
$viewAuth = $context['viewAuth'];
// Roles are global; $tenantScope['ids'] is intentionally not consumed here.
// $canManageAllTenants stays as a resilient hook for future policy extensions.
$canManageAllTenants = $tenantScope['scope'] === 'all';

$errorBag = formErrors();
$errors = [];
$warnings = [];
$form = [
    'description' => '',
    'code' => '',
    'active' => 1,
];
$permissionRepository = app(\MintyPHP\Repository\Access\PermissionRepository::class);
$rolePermissionRepository = app(\MintyPHP\Repository\Access\RolePermissionRepository::class);
$permissions = $permissionRepository->listActive();
$selectedPermissionIds = [];

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

if ($request->isMethod('POST')) {
    $dbSession = app(\MintyPHP\Repository\Support\DatabaseSessionRepository::class);
    $transactionStarted = false;

    try {
        $dbSession->beginTransaction();
        $transactionStarted = true;

        $result = app(\MintyPHP\Service\Access\RoleService::class)->createFromAdmin($request->bodyAll(), $currentUserId);
        $form = $result['form'] ?? $form;
        $warnings = $result['warnings'] ?? [];
        $errorBag->merge($result['errors'] ?? []);
        $selectedPermissionIds = toIntIds($request->body('permission_ids', $selectedPermissionIds));

        if (($result['ok'] ?? false) && !$errorBag->hasAny()) {
            $permissionIds = toIntIds($request->body('permission_ids', []));
            $createdId = (int) ($result['id'] ?? 0);
            if ($createdId <= 0) {
                throw new \RuntimeException('role_create_missing_id');
            }
            $rolePermissionRepository->replaceForRole($createdId, $permissionIds);
            $dbSession->commitTransaction();
            $transactionStarted = false;

            $action = (string) $request->body('action', 'create');
            if ($action === 'create_close') {
                if ($warnings) {
                    Flash::info(implode(' ', $warnings), $closeTarget, 'role_warning');
                }
                Flash::success(t('Role created'), $closeTarget, 'role_created');
                Router::redirect($closeTarget);
            } else {
                $uuid = (string) ($result['uuid'] ?? '');
                if ($uuid !== '') {
                    $target = requestPathWithReturnTarget("admin/roles/edit/{$uuid}", $returnTarget);
                    if ($warnings) {
                        Flash::info(implode(' ', $warnings), $target, 'role_warning');
                    }
                    Flash::success(t('Role created'), $target, 'role_created');
                    Router::redirect($target);
                } else {
                    if ($warnings) {
                        Flash::info(implode(' ', $warnings), $closeTarget, 'role_warning');
                    }
                    Flash::success(t('Role created'), $closeTarget, 'role_created');
                    Router::redirect($closeTarget);
                }
            }
        }
    } catch (\Throwable) {
        if ($transactionStarted) {
            try {
                $dbSession->rollbackTransaction();
            } catch (\Throwable) {
            }
        }
        if (!$errorBag->hasAny()) {
            $errorBag->merge([t('Failed to update role permissions')]);
        }
    }
}

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