<?php

namespace App\Support;

use Picqer\Barcode\BarcodeGenerator as PicqerGenerator;
use Picqer\Barcode\BarcodeGeneratorPNG;
use Picqer\Barcode\BarcodeGeneratorSVG;
use RuntimeException;

/**
 * Thin wrapper around picqer/php-barcode-generator so the rest of the app
 * never imports the dependency directly.
 *
 * Product barcodes are CODE 128: it is the only symbology that accepts the
 * alphanumeric SKU-style values products are auto-assigned (a numeric-only
 * EAN/UPC would reject "JWL-GEN-001" outright).
 */
class BarcodeGenerator
{
    public const TYPE = PicqerGenerator::TYPE_CODE_128;

    /**
     * PNG bytes (for downloads / printing).
     */
    public function png(string $value, int $widthFactor = 2, int $height = 40): string
    {
        $this->assertEncodable($value);

        return (new BarcodeGeneratorPNG)->getBarcode($value, self::TYPE, $widthFactor, $height);
    }

    /**
     * Inline SVG markup (for <img> previews — crisp at any size).
     */
    public function svg(string $value): string
    {
        $this->assertEncodable($value);

        return (new BarcodeGeneratorSVG)->getBarcode($value, self::TYPE);
    }

    /**
     * @return array{content-type: string, bytes: string}
     */
    public function render(string $value, string $format): array
    {
        if ($format === 'svg') {
            return ['content-type' => 'image/svg+xml', 'bytes' => $this->svg($value)];
        }

        return ['content-type' => 'image/png', 'bytes' => $this->png($value)];
    }

    private function assertEncodable(string $value): void
    {
        if (blank($value)) {
            throw new RuntimeException('Cannot render a barcode for an empty value.');
        }
    }
}
