<?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;
}

$gateway = app(BcODataGateway::class);
$result = $gateway->testConnection();

// Optional: diagnose search if ?diag=search query param is set
$searchDiag = null;
$diagQuery = trim((string) $request->query('diag', ''));
if ($diagQuery === 'search') {
    try {
        $searchResults = $gateway->searchCustomers('10');
        $searchDiag = ['status' => 'ok', 'count' => count($searchResults), 'first' => $searchResults[0] ?? null];
    } catch (\Throwable $e) {
        $searchDiag = ['status' => 'error', 'message' => $e->getMessage()];
    }
}

Router::json([
    'ok' => $result['ok'],
    'error' => $result['ok'] ? null : ($result['error'] ?? t('Connection failed')),
    'message' => $result['ok'] ? t('Connection successful') : null,
    'debug' => [
        'url' => $result['url'] ?? null,
        'http_code' => $result['http_code'] ?? null,
        'search_diag' => $searchDiag,
    ],
]);
