<?php

use MintyPHP\Http\ApiAuth;
use MintyPHP\Http\ApiBootstrap;
use MintyPHP\Http\ApiResponse;
use MintyPHP\Service\Access\UserAuthorizationPolicy;
use MintyPHP\Service\User\UserAccountService;
use MintyPHP\Service\User\UserAvatarService;

define('MINTY_ALLOW_OUTPUT', true);

ApiBootstrap::init();
ApiResponse::requireMethod('GET');
$request = requestInput();

$uuid = trim((string) ($id ?? ''));
if ($uuid === '') {
    ApiResponse::notFound();
}

$userAccountService = app(UserAccountService::class);
$userAvatarService = app(UserAvatarService::class);

$user = $userAccountService->findByUuid($uuid);
$userId = (int) ($user['id'] ?? 0);

$authorizationService = app(\MintyPHP\Service\Access\AuthorizationService::class);
$decision = $authorizationService->authorize(UserAuthorizationPolicy::ABILITY_API_USERS_SHOW_GET, [
    'actor_user_id' => ApiAuth::userId(),
    'target_user_id' => $userId,
    'scoped_tenant_id' => ApiAuth::scopedTenantId(),
]);

if (!$decision->isAllowed()) {
    $status = $decision->status() ?: 403;
    $error = $decision->error() ?: 'forbidden';

    if ($status === 404) {
        ApiResponse::notFound($error);
    }

    if ($status === 403) {
        ApiResponse::forbidden($error);
    }

    ApiResponse::error($error, $status);
}

if (!$user) {
    ApiResponse::notFound();
}

$size = $request->hasQuery('size') ? $request->queryInt('size') : null;
$path = $userAvatarService->findAvatarPath($uuid, $size);
if (!$path || !is_file($path)) {
    ApiResponse::notFound();
}

$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);
