<?php

use MintyPHP\Module\Security\SecurityAuthorizationPolicy;
use MintyPHP\Module\Security\Service\SecurityBcGateway;
use MintyPHP\Router;
use MintyPHP\Support\Guard;

Guard::requireLogin();
Guard::requireAbilityOrForbidden(SecurityAuthorizationPolicy::ABILITY_CHECKS_CREATE);
gridRequireGetRequest();

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

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

    return;
}

try {
    $rows = app(SecurityBcGateway::class)->listDomainsForCustomer($debitorNo);
} catch (\Throwable) {
    http_response_code(502);
    Router::json(['error' => 'lookup_failed']);

    return;
}

$items = [];
foreach ($rows as $row) {
    if (!is_array($row)) {
        continue;
    }
    $no = trim((string) ($row['No'] ?? ''));
    $url = trim((string) ($row['URL'] ?? ''));
    if ($no === '') {
        continue;
    }
    $items[] = [
        'value' => $no,
        'label' => $url !== '' ? $url : $no,
        'url' => $url,
    ];
}

Router::json($items);
