#!/usr/bin/env php
<?php

/**
 * Quick CLI diagnostic for helpdesk BC OData connectivity.
 *
 * Usage:  php bin/helpdesk-diagnose.php <customer_no>
 * Example: php bin/helpdesk-diagnose.php 10254
 */

declare(strict_types=1);

chdir(__DIR__ . '/..');
require 'vendor/autoload.php';
require 'config/config.php';
require 'core/Support/helpers.php';

$container = require 'core/App/registerContainer.php';
setAppContainer($container);

use MintyPHP\Module\Helpdesk\Service\BcODataGateway;
use MintyPHP\Module\Helpdesk\Service\HelpdeskSettingsGateway;

$customerNo = trim($argv[1] ?? '');
if ($customerNo === '') {
    echo "Usage: php bin/helpdesk-diagnose.php <customer_no>\n";
    exit(1);
}

$settings = app(HelpdeskSettingsGateway::class);

echo "=== Helpdesk OData Diagnosis ===\n\n";
echo "Base URL:    " . $settings->getODataBaseUrl() . "\n";
echo "Company:     " . $settings->getCompanyName() . "\n";
echo "Auth mode:   " . $settings->getAuthMode() . "\n";
echo "Configured:  " . ($settings->isConfigured() ? 'YES' : 'NO') . "\n";
echo "\n";
echo "Entity URLs:\n";
echo "  Customer: " . $settings->buildEntityUrl(BcODataGateway::ENTITY_CUSTOMER) . "\n";
echo "  Contact:  " . $settings->buildEntityUrl(BcODataGateway::ENTITY_CONTACT) . "\n";
echo "  Tickets:  " . $settings->buildEntityUrl(BcODataGateway::ENTITY_TICKETS) . "\n";
echo "\n";

if (!$settings->isConfigured()) {
    echo "ERROR: Configuration incomplete. Cannot run diagnosis.\n";
    exit(1);
}

$gateway = app(BcODataGateway::class);

echo "Running diagnosis for customer: {$customerNo}\n";
echo str_repeat('─', 60) . "\n\n";

$diagnosis = $gateway->diagnoseCustomer($customerNo);

foreach ($diagnosis as $key => $result) {
    echo "── {$key} ──\n";
    if (is_string($result)) {
        echo "  Error: {$result}\n\n";
        continue;
    }
    echo "  URL:       " . ($result['url'] ?? '?') . "\n";
    echo "  HTTP:      " . ($result['http_code'] ?? '?') . "\n";
    echo "  Count:     " . ($result['count'] ?? 0) . "\n";

    if (!empty($result['error'])) {
        echo "  Error:     " . $result['error'] . "\n";
    }

    if (!empty($result['fields'])) {
        echo "  Fields:    " . implode(', ', $result['fields']) . "\n";
    }

    if (!empty($result['first_record'])) {
        echo "  1st record:\n";
        foreach ($result['first_record'] as $field => $value) {
            $display = is_string($value) ? $value : json_encode($value, JSON_UNESCAPED_UNICODE);
            echo "    {$field}: {$display}\n";
        }
    }
    echo "\n";
}
