<?php

namespace App\Services;

use App\Support\IntegrationConfigResolver;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;

class IntegrationProbe
{
    /**
     * @return array{checked_at: string, esborder: array, sysreflex: array}
     */
    public function probe(): array
    {
        $today = now()->toDateString();
        $checkedAt = now()->toIso8601String();

        return [
            'checked_at' => $checkedAt,
            'esborder' => $this->probeEsborder($today),
            'sysreflex' => $this->probeSysreflex($today),
        ];
    }

    /**
     * @return array{ok: bool, configured: bool, http_status: int|null, latency_ms: float|null, message: string}
     */
    private function probeEsborder(string $date): array
    {
        $base = IntegrationConfigResolver::esborderBaseUrl();
        $key = IntegrationConfigResolver::esborderApiKey();
        if ($base === '' || $key === '') {
            return [
                'ok' => false,
                'configured' => false,
                'http_status' => null,
                'latency_ms' => null,
                'message' => 'URL atau API key SysOrder belum diatur (Pengaturan atau .env).',
            ];
        }

        $url = $base.'/api/reports/consolidated';
        $started = hrtime(true);
        try {
            $response = Http::timeout(8)
                ->withHeaders([
                    'Accept' => 'application/json',
                    'Authorization' => 'Bearer '.$key,
                ])
                ->get($url, ['date_from' => $date, 'date_to' => $date]);
        } catch (\Throwable $e) {
            return [
                'ok' => false,
                'configured' => true,
                'http_status' => null,
                'latency_ms' => null,
                'message' => $e->getMessage(),
            ];
        }
        $ms = (hrtime(true) - $started) / 1e6;

        if (! $response->successful()) {
            return [
                'ok' => false,
                'configured' => true,
                'http_status' => $response->status(),
                'latency_ms' => round($ms, 2),
                'message' => 'HTTP '.$response->status().': '.Str::limit($response->body(), 200),
            ];
        }

        $json = $response->json();
        if (! is_array($json) || ! array_key_exists('grand_total', $json)) {
            return [
                'ok' => false,
                'configured' => true,
                'http_status' => $response->status(),
                'latency_ms' => round($ms, 2),
                'message' => 'Respons bukan JSON laporan yang diharapkan.',
            ];
        }

        return [
            'ok' => true,
            'configured' => true,
            'http_status' => $response->status(),
            'latency_ms' => round($ms, 2),
            'message' => 'OK — endpoint /api/reports/consolidated merespons.',
        ];
    }

    /**
     * @return array{ok: bool, configured: bool, http_status: int|null, latency_ms: float|null, message: string}
     */
    private function probeSysreflex(string $date): array
    {
        $base = IntegrationConfigResolver::sysreflexBaseUrl();
        $token = IntegrationConfigResolver::sysreflexApiToken();
        if ($base === '' || $token === '') {
            return [
                'ok' => false,
                'configured' => false,
                'http_status' => null,
                'latency_ms' => null,
                'message' => 'URL atau token sysReflex belum diatur (Pengaturan atau .env).',
            ];
        }

        $url = $base.'/api/owner/summary';
        $started = hrtime(true);
        try {
            $response = Http::timeout(8)
                ->withHeaders([
                    'Accept' => 'application/json',
                    'Authorization' => 'Bearer '.$token,
                ])
                ->get($url, ['date_from' => $date, 'date_to' => $date]);
        } catch (\Throwable $e) {
            return [
                'ok' => false,
                'configured' => true,
                'http_status' => null,
                'latency_ms' => null,
                'message' => $e->getMessage(),
            ];
        }
        $ms = (hrtime(true) - $started) / 1e6;

        if (! $response->successful()) {
            return [
                'ok' => false,
                'configured' => true,
                'http_status' => $response->status(),
                'latency_ms' => round($ms, 2),
                'message' => 'HTTP '.$response->status().': '.Str::limit($response->body(), 200),
            ];
        }

        $json = $response->json();
        if (! is_array($json) || ($json['source'] ?? '') !== 'sysreflex') {
            return [
                'ok' => false,
                'configured' => true,
                'http_status' => $response->status(),
                'latency_ms' => round($ms, 2),
                'message' => 'Respons bukan JSON owner summary yang diharapkan.',
            ];
        }

        return [
            'ok' => true,
            'configured' => true,
            'http_status' => $response->status(),
            'latency_ms' => round($ms, 2),
            'message' => 'OK — endpoint /api/owner/summary merespons.',
        ];
    }
}
