<?php

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

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

Guard::requireLogin();
$authorizationService = app(\MintyPHP\Service\Access\AuthorizationService::class);
$tenantAvatarService = app(\MintyPHP\Service\Tenant\TenantAvatarService::class);

$uuid = trim((string) (requestInput()->queryAll()['uuid'] ?? ''));
$size = isset(requestInput()->queryAll()['size']) ? (int) requestInput()->queryAll()['size'] : null;
if (!$tenantAvatarService->isValidUuid($uuid)) {
    http_response_code(404);
    return;
}

$tenant = app(\MintyPHP\Service\Tenant\TenantService::class)->findByUuid($uuid);
$tenantId = (int) ($tenant['id'] ?? 0);
$currentUserId = (int) ($session['user']['id'] ?? 0);
if ($tenantId <= 0) {
    http_response_code(404);
    return;
}
$decision = $authorizationService->authorize(TenantAuthorizationPolicy::ABILITY_ADMIN_TENANTS_AVATAR_VIEW, [
    'actor_user_id' => $currentUserId,
    'target_tenant_id' => $tenantId,
]);
if (!$decision->isAllowed()) {
    http_response_code(403);
    return;
}

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

$mime = $tenantAvatarService->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);
