<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;
use Throwable;

class PythonRecommendationService
{
    protected string $baseUrl;
    protected int $timeout;

    public function __construct()
    {
        $this->baseUrl = rtrim((string) config('services.python_api.url'), '/');
        $this->timeout = (int) config('services.python_api.timeout', 30);
    }

    public function health(): array
    {
        try {
            if ($this->baseUrl === '') {
                return [
                    'success' => false,
                    'status_code' => 500,
                    'data' => null,
                    'message' => 'PYTHON_API_URL belum diatur pada file .env.',
                ];
            }

            $response = Http::timeout($this->timeout)
                ->acceptJson()
                ->get($this->baseUrl . '/health');

            return [
                'success' => $response->successful(),
                'status_code' => $response->status(),
                'data' => $response->json(),
                'message' => $response->successful()
                    ? 'Laravel berhasil terhubung ke Flask API.'
                    : 'Laravel gagal membaca Flask API.',
            ];
        } catch (Throwable $e) {
            return [
                'success' => false,
                'status_code' => 500,
                'data' => null,
                'message' => 'Tidak dapat terhubung ke Flask API: ' . $e->getMessage(),
            ];
        }
    }

    public function predict(array $payload): array
    {
        try {
            if ($this->baseUrl === '') {
                return [
                    'success' => false,
                    'status_code' => 500,
                    'data' => null,
                    'message' => 'PYTHON_API_URL belum diatur pada file .env.',
                ];
            }

            $response = Http::timeout($this->timeout)
                ->acceptJson()
                ->asJson()
                ->post($this->baseUrl . '/predict', $payload);

            $json = $response->json();

            return [
                'success' => $response->successful(),
                'status_code' => $response->status(),
                'data' => $json,
                'message' => $response->successful()
                    ? 'Prediksi berhasil diproses oleh Flask API.'
                    : ($json['message'] ?? $response->body() ?? 'Prediksi gagal diproses oleh Flask API.'),
            ];
        } catch (Throwable $e) {
            return [
                'success' => false,
                'status_code' => 500,
                'data' => null,
                'message' => 'Koneksi ke Flask API gagal: ' . $e->getMessage(),
            ];
        }
    }
}