<?php

use MintyPHP\Service\Tenant\TenantServicesFactory;
use MintyPHP\Support\Guard;

define('MINTY_ALLOW_OUTPUT', true);

Guard::requireLogin();
$tenantAvatarService = (new TenantServicesFactory())->createTenantAvatarService();

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

$tenant = directoryServicesFactory()->createTenantService()->findByUuid($uuid);
$tenantId = (int) ($tenant['id'] ?? 0);
$currentUserId = (int) ($_SESSION['user']['id'] ?? 0);
if ($tenantId <= 0) {
    http_response_code(404);
    return;
}
if (!directoryServicesFactory()->createDirectoryScopeGateway()->canAccess('tenants', $tenantId, $currentUserId)) {
    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);
