<?php

declare(strict_types=1);

use App\Domain\QrCode\ValueObject\GaloisField;
use App\Domain\QrCode\ValueObject\Polynomial;

test('Polynomial kann erstellt werden', function () {
    $field = new GaloisField();
    $poly = new Polynomial($field, [1, 2, 3]); // x^2 + 2x + 3

    expect($poly->getCoefficients())->toBe([1, 2, 3]);
    expect($poly->getDegree())->toBe(2);
});

test('Polynomial entfernt führende Nullen', function () {
    $field = new GaloisField();
    $poly = new Polynomial($field, [0, 0, 1, 2]); // x + 2

    expect($poly->getCoefficients())->toBe([1, 2]);
    expect($poly->getDegree())->toBe(1);
});

test('Polynomial kann an Stelle x ausgewertet werden', function () {
    $field = new GaloisField();
    $poly = new Polynomial($field, [1, 0, 1]); // x^2 + 1

    expect($poly->evaluateAt(0))->toBe(1);
    expect($poly->evaluateAt(1))->toBe(0); // 1^2 + 1 = 2 = 0 in GF(2)
    expect($poly->evaluateAt(2))->toBe(5); // 2^2 + 1 = 5
});

test('Polynomial Addition funktioniert', function () {
    $field = new GaloisField();
    $poly1 = new Polynomial($field, [1, 2]); // x + 2
    $poly2 = new Polynomial($field, [3, 4]); // 3x + 4

    $sum = $poly1->add($poly2);

    // In GF(2^8) ist Addition = XOR, daher 1⊕3=2, 2⊕4=6
    expect($sum->getCoefficients())->toBe([2, 6]);
});

test('Polynomial Multiplikation funktioniert', function () {
    $field = new GaloisField();
    $poly1 = new Polynomial($field, [1, 1]); // x + 1
    $poly2 = new Polynomial($field, [1, 0, 1]); // x^2 + 1

    $product = $poly1->multiply($poly2);

    // (x + 1)(x^2 + 1) = x^3 + x^2 + x + 1
    expect($product->getCoefficients())->toBe([1, 1, 1, 1]);
});

test('Polynomial Division funktioniert', function () {
    $field = new GaloisField();
    $poly1 = new Polynomial($field, [1, 0, 1]); // x^2 + 1
    $poly2 = new Polynomial($field, [1, 1]); // x + 1

    $result = $poly1->divideAndRemainder($poly2);

    // (x^2 + 1) ÷ (x + 1) = x - 1 + 2/(x+1)
    // In GF(2^8): Quotient = x - 1 = x + 1, Rest = 2
    expect($result['quotient']->getCoefficients())->toEqual([1, 1]);
    expect($result['remainder']->getCoefficients())->toEqual([0]);
});

test('Generator Polynom kann korrekt erstellt werden', function () {
    $field = new GaloisField();
    $generator = Polynomial::buildGenerator($field, 3);

    // Erwartetes Ergebnis für Grad 3
    expect($generator->getDegree())->toBe(3);
    expect(count($generator->getCoefficients()))->toBe(4);
});
