<?php

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

$session = app(SessionStoreInterface::class)->all();
Guard::requireLogin();
$authorizationService = app(\MintyPHP\Service\Access\AuthorizationService::class);
$userAccountService = app(\MintyPHP\Service\User\UserAccountService::class);
$userAvatarService = app(\MintyPHP\Service\User\UserAvatarService::class);

if ((requestInput()->method()) !== 'POST') {
    Router::redirect('admin');
    return;
}

$errorBag = formErrors();
$uuid = trim((string) ($id ?? ''));
if (!$userAvatarService->isValidUuid($uuid)) {
    $errorBag->addGlobal('User not found');
    flashFormErrors($errorBag, 'admin', 'user_avatar_delete');
    Router::redirect('admin');
    return;
}

$currentUserId = (int) ($session['user']['id'] ?? 0);
$user = $uuid !== '' ? $userAccountService->findByUuid($uuid) : null;
$userId = (int) ($user['id'] ?? 0);
$decision = $authorizationService->authorize(UserAuthorizationPolicy::ABILITY_ADMIN_USERS_AVATAR_DELETE, [
    'actor_user_id' => $currentUserId,
    'target_user_id' => $userId,
]);
if (!$decision->isAllowed()) {
    Router::redirect('error/forbidden');
    return;
}

$userAvatarService->delete($uuid);
Flash::success('Avatar removed', "admin/users/edit/{$uuid}", 'avatar_removed');
Router::redirect("admin/users/edit/{$uuid}");
