<?php

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

Guard::requireLogin();
Guard::requireAbilityOrForbidden(HelpdeskAuthorizationPolicy::ABILITY_ACCESS);

$request = requestInput();
$ticketNo = trim((string) ($id ?? ''));
$fromCustomerNo = trim((string) $request->query('from', ''));

if ($ticketNo === '') {
    http_response_code(400);
    $ticket = null;
    return;
}

$gateway = app(BcODataGateway::class);

$connectionError = false;
try {
    $ticket = $gateway->getTicket($ticketNo);
} catch (\Throwable) {
    $ticket = null;
    $connectionError = true;
}

if ($ticket === null && !$connectionError) {
    http_response_code(404);
    return;
}

$ticketCustomerNo = $fromCustomerNo;
$ticketDescription = (string) ($ticket['Description'] ?? $ticketNo);
$ticketCommunicationUrl = lurl('helpdesk/ticket-communication-data');
