<?php

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

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

$request = requestInput();
if ($request->method() !== 'POST') {
    http_response_code(405);
    Router::json(['ok' => false, 'error' => 'method_not_allowed']);

    return;
}

if (!Session::checkCsrfToken()) {
    http_response_code(403);
    Router::json(['ok' => false, 'error' => 'csrf_expired']);

    return;
}

$settingsGateway = app(HelpdeskSettingsGateway::class);
if (!$settingsGateway->isConfigured()) {
    Router::json(['ok' => false, 'error' => t('Configuration incomplete')]);

    return;
}

$body = $request->bodyAll();
$customerNo = trim((string) ($body['customer_no'] ?? ''));
if ($customerNo === '') {
    Router::json(['ok' => false, 'error' => t('Please provide a customer number')]);

    return;
}

$gateway = app(BcODataGateway::class);
$diagnosis = $gateway->diagnoseCustomer($customerNo);

Router::json([
    'ok' => true,
    'customer_no' => $customerNo,
    'diagnosis' => $diagnosis,
]);
