<?php

namespace App\Filament\Resources\AduanResource\Pages;

use App\Filament\Resources\AduanResource;
use Filament\Resources\Pages\CreateRecord;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class CreateAduan extends CreateRecord
{
    protected static string $resource = AduanResource::class;

    protected function afterCreate(): void
    {
        $aduan = $this->record;

        try {
            $response = Http::timeout(10)->post('http://127.0.0.1:5000/predict', [
                'text' => $aduan->isi_aduan
            ]);

            $result = $response->json();

            // ✅ HANDLE MULTI KATEGORI (ARRAY → STRING)
            $kategori = isset($result['kategori']) && is_array($result['kategori'])
                ? implode(', ', $result['kategori'])
                : ($result['kategori'] ?? 'tidak diketahui');

            // ✅ PRIORITAS
            $prioritas = $result['prioritas'] ?? 'biasa';

            // ✅ CONFIDENCE SCORE
            $confidence = $result['confidence'] ?? null;

            // ✅ UPDATE DATA
            $aduan->update([
                'kategori'         => $kategori,
                'prioritas'        => $prioritas,
                'confidence_score' => $confidence,
            ]);

        } catch (\Exception $e) {
            Log::error('ML API Error: ' . $e->getMessage());

            // Fallback jika ML API tidak tersedia
            $aduan->update([
                'kategori'         => 'error - ml api tidak tersedia',
                'prioritas'        => 'biasa',
                'confidence_score' => null,
            ]);
        }
    }
}
