<?php

use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Router;
use MintyPHP\Service\Access\TenantAuthorizationPolicy;
use MintyPHP\Support\Flash;
use MintyPHP\Support\Guard;

$session = app(SessionStoreInterface::class)->all();
Guard::requireLogin();
$authorizationService = app(\MintyPHP\Service\Access\AuthorizationService::class);
$tenantFaviconService = app(\MintyPHP\Service\Tenant\TenantFaviconService::class);

if ((requestInput()->method()) !== 'POST') {
    Router::redirect('admin/tenants');
    return;
}

$errorBag = formErrors();
$uuid = trim((string) ($id ?? ''));
if (!$tenantFaviconService->isValidUuid($uuid)) {
    $errorBag->addGlobal('Tenant not found');
    flashFormErrors($errorBag, 'admin/tenants', 'tenant_favicon_delete');
    Router::redirect('admin/tenants');
    return;
}

$tenant = app(\MintyPHP\Service\Tenant\TenantService::class)->findByUuid($uuid);
$tenantId = (int) ($tenant['id'] ?? 0);
$currentUserId = (int) ($session['user']['id'] ?? 0);
$decision = $authorizationService->authorize(TenantAuthorizationPolicy::ABILITY_ADMIN_TENANTS_MEDIA_UPDATE, [
    'actor_user_id' => $currentUserId,
    'target_tenant_id' => $tenantId,
]);
if (!$decision->isAllowed()) {
    Router::redirect('error/forbidden');
    return;
}

$tenantFaviconService->delete($uuid);
Flash::success('Favicon removed', "admin/tenants/edit/{$uuid}", 'tenant_favicon_removed');
Router::redirect("admin/tenants/edit/{$uuid}");
