<?php

use MintyPHP\Service\Tenant\TenantServicesFactory;

define('MINTY_ALLOW_OUTPUT', true);

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

$tenant = directoryServicesFactory()->createTenantService()->findByUuid($uuid);
if (!$tenant || (string) ($tenant['status'] ?? 'active') !== 'active') {
    http_response_code(404);
    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: public, max-age=300');
header('Content-Length: ' . filesize($path));
readfile($path);
