<?php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
use JsonException;

class OrderPrintRequested implements ShouldBroadcastNow
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public function __construct(public array $payload)
    {
    }

    public function broadcastOn(): Channel
    {
        return new Channel('print-orders');
    }

    public function broadcastAs(): string
    {
        return 'order.print';
    }

    public function broadcastWith(): array
    {
        return $this->compressIfNeeded($this->payload);
    }

    private function compressIfNeeded(array $payload): array
    {
        try {
            $rawJson = json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR);
        } catch (JsonException) {
            return $payload;
        }

        if (! is_string($rawJson)) {
            return $payload;
        }

        // Target aman untuk limit payload kecil (sekitar 1KB).
        $limit = 950;
        if (strlen($rawJson) <= $limit) {
            return $payload;
        }

        $compressed = gzencode($rawJson, 9);
        if ($compressed === false) {
            return $payload;
        }

        $b64 = base64_encode($compressed);
        if ($b64 === '') {
            return $payload;
        }

        // Paket terkompres untuk agent Python.
        return [
            '_compressed' => 1,
            '_encoding' => 'gzip+base64+json',
            '_payload' => $b64,
        ];
    }
}
