<?php

namespace App\Repositories\Ecommerce\Product\Barcode;

class BarcodeRepository
{
    /**
     * Default barcode generator
     */
    public static function generateBarcode(): int|string|float
    {
        return rand(1000000000, 9999999999);
    }

    /**
     * Generate a random 12-digit number.
     */
    public static function generateRandomNumber(int $length = 12): string
    {
        return collect(range(1, $length))
            ->map(fn () => random_int(0, 9))
            ->join('');
    }

    /**
     * Calculate EAN-13 checksum for a given number.
     */
    public static function calculateEAN13Checksum(string $number): int
    {
        $sum = collect(str_split($number))
            ->take(12)
            ->reduce(
                callback: fn ($carry, $item, $key) => $carry + ($key % 2 === 0 ? $item : $item * 3),
                initial: 0
            );

        return (10 - ($sum % 10)) % 10;
    }

    /**
     * Generate a complete EAN-13 barcode number.
     */
    public static function generateEan13Number(): string
    {
        $randomNumber = static::generateRandomNumber();

        return $randomNumber.static::calculateEAN13Checksum($randomNumber);
    }

    /**
     * Image generator route
     */
    public static function imageGeneratorRoute(): string
    {
        return route('barcode-generator');
    }
}
