<?php

use MintyPHP\Service\Tenant\TenantServicesFactory;

define('MINTY_ALLOW_OUTPUT', true);

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

$tenant = app(\MintyPHP\Service\Directory\DirectoryServicesFactory::class)->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);
