<?php

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

$session = app(SessionStoreInterface::class)->all();
define('MINTY_ALLOW_OUTPUT', true);

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

$uuid = trim((string) (requestInput()->queryAll()['uuid'] ?? ''));
$size = isset(requestInput()->queryAll()['size']) ? (int) requestInput()->queryAll()['size'] : null;
if (!$userAvatarService->isValidUuid($uuid)) {
    http_response_code(404);
    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_VIEW, [
    'actor_user_id' => $currentUserId,
    'target_user_id' => $userId,
]);
if (!$decision->isAllowed()) {
    http_response_code(403);
    return;
}

$path = $userAvatarService->findAvatarPath($uuid, $size);
if (!$path || !is_file($path)) {
    http_response_code(404);
    return;
}

$mime = $userAvatarService->detectMime($path);
header('Content-Type: ' . $mime);
header('X-Content-Type-Options: nosniff');
header('Content-Security-Policy: sandbox');
header('Cache-Control: private, max-age=300');
header('Content-Length: ' . filesize($path));
readfile($path);
