<?php

use MintyPHP\Http\ApiAuth;
use MintyPHP\Http\ApiBootstrap;
use MintyPHP\Http\ApiResponse;
use MintyPHP\Service\Tenant\TenantServicesFactory;

define('MINTY_ALLOW_OUTPUT', true);

ApiBootstrap::init();
ApiResponse::requireMethod('GET');
ApiResponse::requireAbility(\MintyPHP\Service\Access\OperationsAuthorizationPolicy::ABILITY_API_TENANTS_VIEW);
$request = requestInput();

$uuid = trim((string) ($id ?? ''));
if ($uuid === '') {
    http_response_code(404);
    header('Content-Type: application/json');
    echo json_encode(['error' => 'not_found']);
    return;
}

$tenantAvatarService = (app(TenantServicesFactory::class))->createTenantAvatarService();

if (!$tenantAvatarService->isValidUuid($uuid)) {
    http_response_code(404);
    header('Content-Type: application/json');
    echo json_encode(['error' => 'not_found']);
    return;
}

$tenant = app(\MintyPHP\Service\Directory\DirectoryServicesFactory::class)->createTenantService()->findByUuid($uuid);
$tenantId = (int) ($tenant['id'] ?? 0);
if ($tenantId <= 0) {
    http_response_code(404);
    header('Content-Type: application/json');
    echo json_encode(['error' => 'not_found']);
    return;
}

ApiAuth::requireResourceAccess('tenants', $tenantId);

$size = $request->hasQuery('size') ? $request->queryInt('size') : null;
$path = $tenantAvatarService->findAvatarPath($uuid, $size);
if (!$path || !is_file($path)) {
    http_response_code(404);
    header('Content-Type: application/json');
    echo json_encode(['error' => 'not_found']);
    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);
