<?php

namespace Tests\Unit\Services\Badges;

use App\Models\BadgePrintLog;
use App\Services\Badges\BadgePrintLogService;
use App\Services\Badges\BadgeTextFormatter;
use Illuminate\Support\Facades\Log;
use Mockery;
use Tests\TestCase;

class BadgePrintLogServiceTest extends TestCase
{
    protected function tearDown(): void
    {
        Mockery::close();
        parent::tearDown();
    }

    public function test_get_status_normalizes_ids_before_calling_model(): void
    {
        $model = Mockery::mock(BadgePrintLog::class);
        $formatter = new BadgeTextFormatter();

        $expected = [
            5 => ['count' => 2, 'last_printed_at' => '2026-03-06 10:00:00', 'last_printed_by' => 1],
        ];

        $model->shouldReceive('getStatus')
            ->once()
            ->with([5, 7], '2025-2026')
            ->andReturn($expected);

        $service = new BadgePrintLogService($model, $formatter);

        $result = $service->getStatus(['5', '7', '5', ''], '2025-2026');

        $this->assertSame($expected, $result);
    }

    public function test_log_normalizes_ids_and_returns_inserted_count(): void
    {
        $model = Mockery::mock(BadgePrintLog::class);
        $formatter = new BadgeTextFormatter();

        $model->shouldReceive('logPrints')
            ->once()
            ->with(
                [10, 20],
                99,
                '2025-2026',
                ['10' => 'Teacher'],
                ['10' => '3-A'],
                1
            )
            ->andReturn(2);

        $service = new BadgePrintLogService($model, $formatter);

        $result = $service->log(
            userIds: ['10', '20', '10'],
            actorId: 99,
            schoolYear: '2025-2026',
            rolesMap: ['10' => 'Teacher'],
            classesMap: ['10' => '3-A'],
            copies: 1
        );

        $this->assertSame(2, $result);
    }

    public function test_log_safely_swallows_exceptions_and_logs_error(): void
    {
        Log::spy();

        $model = Mockery::mock(BadgePrintLog::class);
        $formatter = new BadgeTextFormatter();

        $model->shouldReceive('logPrints')
            ->once()
            ->andThrow(new \RuntimeException('table missing'));

        $service = new BadgePrintLogService($model, $formatter);

        $service->logSafely(
            userIds: [1, 2],
            actorId: 5,
            schoolYear: '2025-2026'
        );

        Log::shouldHaveReceived('error')->once();
        $this->assertTrue(true);
    }
}