<?php

use MintyPHP\Module\Helpdesk\HelpdeskAuthorizationPolicy;
use MintyPHP\Module\Helpdesk\Service\BcODataGateway;
use MintyPHP\Router;
use MintyPHP\Support\Guard;

Guard::requireLogin();
Guard::requireAbilityOrForbidden(HelpdeskAuthorizationPolicy::ABILITY_HANDOVERS_CREATE);
gridRequireGetRequest();

$request = requestInput();
$debitorNo = trim((string) $request->query('debitor_no', ''));

if ($debitorNo === '') {
    Router::json([]);

    return;
}

try {
    $domains = app(BcODataGateway::class)->getDomainsForCustomer($debitorNo);
} catch (\Throwable) {
    Router::json([]);

    return;
}

$items = [];
foreach ($domains as $domain) {
    $no = trim((string) ($domain['No'] ?? ''));
    $url = trim((string) ($domain['URL'] ?? ''));
    if ($no === '') {
        continue;
    }

    $items[] = [
        'value' => $no,
        'label' => $url !== '' ? $url : $no,
        'url' => $url,
    ];
}

Router::json($items);
