<?php

use MintyPHP\Http\ApiAuth;
use MintyPHP\Http\ApiBootstrap;
use MintyPHP\Http\ApiResponse;
use MintyPHP\Service\Tenant\TenantLogoService;
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 === '') {
    ApiResponse::notFound();
}

$tenantLogoService = (app(TenantServicesFactory::class))->createTenantLogoService();

if (!$tenantLogoService->isValidUuid($uuid)) {
    ApiResponse::notFound();
}

$tenant = app(\MintyPHP\Service\Directory\DirectoryServicesFactory::class)->createTenantService()->findByUuid($uuid);
$tenantId = (int) ($tenant['id'] ?? 0);
if ($tenantId <= 0) {
    ApiResponse::notFound();
}

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

$size = $request->hasQuery('size') ? $request->queryInt('size') : null;
$theme = $request->hasQuery('theme') ? strtolower(trim((string) $request->queryAll()['theme'])) : TenantLogoService::THEME_LIGHT;
if (!$tenantLogoService->isValidTheme($theme)) {
    $theme = TenantLogoService::THEME_LIGHT;
}
$path = $tenantLogoService->findLogoPath($uuid, $theme, $size);
if (!$path || !is_file($path)) {
    // Fallback to the other theme so single-theme tenants still respond.
    $otherTheme = $theme === TenantLogoService::THEME_DARK ? TenantLogoService::THEME_LIGHT : TenantLogoService::THEME_DARK;
    $path = $tenantLogoService->findLogoPath($uuid, $otherTheme, $size);
}
if (!$path || !is_file($path)) {
    ApiResponse::notFound();
}

$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);
