<?php

declare(strict_types=1);

namespace App\Framework\View\Table\Formatters;

use App\Framework\View\Table\CellFormatter;

final readonly class BooleanFormatter implements CellFormatter
{
    public function __construct(
        private string $trueText = 'Yes',
        private string $falseText = 'No',
        private ?string $nullText = null,
        private bool $useBadges = false
    ) {
    }

    public function format(mixed $value): string
    {
        if ($value === null) {
            return $this->nullText ?? '';
        }

        $isTrue = match (true) {
            is_bool($value) => $value,
            is_string($value) => in_array(strtolower($value), ['true', '1', 'yes', 'on', 'enabled']),
            is_numeric($value) => $value > 0,
            default => (bool) $value
        };

        $text = $isTrue ? $this->trueText : $this->falseText;

        if ($this->useBadges) {
            $badgeClass = $isTrue ? 'badge-success' : 'badge-secondary';

            return "<span class=\"badge {$badgeClass}\">{$text}</span>";
        }

        return $text;
    }

    public static function german(): self
    {
        return new self('Ja', 'Nein');
    }

    public static function enabled(): self
    {
        return new self('Enabled', 'Disabled');
    }

    public static function withBadges(): self
    {
        return new self('Yes', 'No', null, true);
    }

    public static function germanWithBadges(): self
    {
        return new self('Ja', 'Nein', null, true);
    }
}
