<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Http;

class SendRegisterApiExportCommand extends Command
{
    protected $signature = 'register-api:send-export
        {file : Path file JSON hasil register-api:export}
        {--url= : URL endpoint registerApi, default APP_URL/registerpasien}
        {--delay=0 : Jeda antar kirim dalam milidetik}
        {--limit=0 : Batasi jumlah data yang dikirim, 0 berarti semua}
        {--start=0 : Mulai dari index data ke-n, 0 berarti dari awal}
        {--dry-run : Tampilkan payload tanpa mengirim}
        {--stop-on-error : Berhenti jika ada request gagal}';

    protected $description = 'Simulasi kirim payload registerApi dari file JSON export seolah-olah dikirim oleh SIMRS.';

    public function handle(): int
    {
        $file = (string) $this->argument('file');
        if (!File::exists($file) || !is_readable($file)) {
            $this->error('File JSON tidak ditemukan atau tidak bisa dibaca: ' . $file);
            return Command::FAILURE;
        }

        $content = File::get($file);
        $decoded = json_decode($content, true);
        if (!is_array($decoded)) {
            $this->error('File bukan JSON valid.');
            return Command::FAILURE;
        }

        $rows = $this->extractRows($decoded);
        if (empty($rows)) {
            $this->warn('Tidak ada data untuk dikirim.');
            return Command::SUCCESS;
        }

        $start = max(0, (int) $this->option('start'));
        $limit = max(0, (int) $this->option('limit'));
        $delay = max(0, (int) $this->option('delay'));
        $endpoint = $this->endpoint();

        $rows = array_slice($rows, $start, $limit > 0 ? $limit : null);
        $total = count($rows);
        $success = 0;
        $failed = 0;

        $this->info('Endpoint: ' . $endpoint);
        $this->info('Total payload: ' . $total);

        foreach ($rows as $index => $payload) {
            $sequence = $start + $index + 1;
            $label = $payload['nomor_lab'] ?? $payload['norm'] ?? $sequence;

            if ($this->option('dry-run')) {
                $this->line('[' . $sequence . '] DRY RUN ' . $label . ': ' . json_encode($payload, JSON_UNESCAPED_SLASHES));
                $success++;
                continue;
            }

            $response = Http::asJson()
                ->acceptJson()
                ->timeout(120)
                ->post($endpoint, $payload);

            if ($response->successful()) {
                $success++;
                $this->line('[' . $sequence . '] OK ' . $label . ' HTTP ' . $response->status() . ' ' . $response->body());
            } else {
                $failed++;
                $this->error('[' . $sequence . '] GAGAL ' . $label . ' HTTP ' . $response->status() . ' ' . $response->body());

                if ($this->option('stop-on-error')) {
                    break;
                }
            }

            if ($delay > 0 && $index < $total - 1) {
                usleep($delay * 1000);
            }
        }

        $this->info('Selesai. Berhasil: ' . $success . ', gagal: ' . $failed);

        return $failed > 0 ? Command::FAILURE : Command::SUCCESS;
    }

    private function extractRows(array $decoded): array
    {
        if (isset($decoded['data']) && is_array($decoded['data'])) {
            return $decoded['data'];
        }

        if (array_is_list($decoded)) {
            return $decoded;
        }

        return [$decoded];
    }

    private function endpoint(): string
    {
        $url = (string) $this->option('url');
        if ($url !== '') {
            return $url;
        }

        return rtrim((string) config('app.url'), '/') . '/registerpasien';
    }
}
