<?php

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

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

Guard::requireLogin();
$authorizationService = app(\MintyPHP\Service\Access\AuthorizationService::class);
$tenantLogoService = app(TenantLogoService::class);

$query = requestInput()->queryAll();
$uuid = trim((string) ($query['uuid'] ?? ''));
$theme = strtolower(trim((string) ($query['theme'] ?? '')));
$size = isset($query['size']) ? (int) $query['size'] : null;
if (!$tenantLogoService->isValidUuid($uuid) || !$tenantLogoService->isValidTheme($theme)) {
    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_LOGO_VIEW, [
    'actor_user_id' => $currentUserId,
    'target_tenant_id' => $tenantId,
]);
if (!$decision->isAllowed()) {
    http_response_code(403);
    return;
}

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

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