<?php

namespace Tests\Unit\Services\Badges;

use App\Services\Badges\BadgeTextFormatter;
use FPDF;
use Tests\TestCase;

class BadgeTextFormatterTest extends TestCase
{
    protected BadgeTextFormatter $formatter;

    protected function setUp(): void
    {
        parent::setUp();
        $this->formatter = new BadgeTextFormatter();
    }

    public function test_normalize_ids_filters_and_deduplicates(): void
    {
        $result = $this->formatter->normalizeIds([
            ' 5 ',
            '',
            null,
            '7',
            5,
            '0',
            -1,
            '12',
        ]);

        $this->assertSame([5, 7, 12], $result);
    }

    public function test_norm_removes_extra_spaces_and_control_chars(): void
    {
        $input = "  Head \x07   of   School  ";
        $result = $this->formatter->norm($input);

        $this->assertSame('Head of School', $result);
    }

    public function test_format_role_handles_special_words_and_acronyms(): void
    {
        $this->assertSame('Head of School', $this->formatter->formatRole('HEAD_OF_SCHOOL'));
        $this->assertSame('Teacher Assistant', $this->formatter->formatRole('teacher_assistant'));
        $this->assertSame('HR Manager', $this->formatter->formatRole('hr manager'));
        $this->assertSame('PTA Head', $this->formatter->formatRole('pta head'));
    }

    public function test_format_roles_csv_formats_each_role(): void
    {
        $result = $this->formatter->formatRolesCsv('teacher_assistant, head_of_school, hr');

        $this->assertSame('Teacher Assistant, Head of School, HR', $result);
    }

    public function test_format_class_normalizes_known_values(): void
    {
        $this->assertSame('KG', $this->formatter->formatClass('kindergarten'));
        $this->assertSame('KG', $this->formatter->formatClass('kg'));
        $this->assertSame('Youth', $this->formatter->formatClass('youth'));
        $this->assertSame('3-A', $this->formatter->formatClass('3-A'));
    }

    public function test_resolve_role_prefers_first_available_candidate(): void
    {
        $info = [
            'role_name' => '',
            'roles' => 'teacher_assistant, admin',
            'job_title' => 'ignored because roles wins first',
        ];

        $result = $this->formatter->resolveRole($info);

        $this->assertSame('teacher_assistant', $result);
    }

    public function test_to_pdf_returns_string(): void
    {
        $result = $this->formatter->toPdf('Al Rahma Sunday School');

        $this->assertIsString($result);
        $this->assertNotSame('', $result);
    }

    public function test_fit_text_returns_size_within_bounds(): void
    {
        $pdf = new FPDF();
        $pdf->AddPage();
        $pdf->SetFont('Arial', '', 12);

        $size = $this->formatter->fitText($pdf, 'Very Long Badge Label Text', 11, 7, 50);

        $this->assertGreaterThanOrEqual(7, $size);
        $this->assertLessThanOrEqual(11, $size);
    }
}