<?php

namespace Tests\Feature\Api\V1\Workflows;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Tests\Concerns\SeedsE2ETestFixtures;
use Tests\TestCase;

/**
 * Scenario G: Print and Badge Workflow.
 *
 * @see docs/alrahma_end_to_end_use_case_test_plan.md Scenario G
 */
class ScenarioGPrintBadgeTest extends TestCase
{
    use RefreshDatabase;
    use SeedsE2ETestFixtures;

    public function test_print_request_badge_log_and_scan_workflow(): void
    {
        $world = $this->seedTeacherClassWithStudent();
        $teacher = $world['teacher'];
        $classSectionId = $world['class_section_id'];
        $admin = $this->actingAsApiAdministrator();

        $this->actingAs($teacher, 'api');
        $create = $this->postJson('/api/v1/print-requests/hand-copy', [
            'class_id' => $classSectionId,
            'num_copies' => 2,
            'required_by' => '2026-09-13 11:00:00',
            'pickup_method' => 'Self Pickup',
        ]);
        $create->assertCreated();
        $requestId = (int) $create->json('data.print_request.id');

        $this->actingAs($admin, 'api');
        foreach (['assigned', 'done', 'delivered'] as $status) {
            $this->patchJson('/api/v1/print-requests/' . $requestId . '/status', [
                'status' => $status,
            ])->assertOk();
        }

        $this->assertDatabaseHas('print_requests', [
            'id' => $requestId,
            'status' => 'delivered',
        ]);

        $badgeTag = 'E2E-BADGE-' . random_int(10000, 99999);
        DB::table('users')->where('id', $teacher->id)->update(['rfid_tag' => $badgeTag]);

        $this->postJson('/api/v1/badges/log-print', [
            'user_ids' => [$teacher->id],
            'school_year' => self::E2E_SCHOOL_YEAR,
            'roles' => [(string) $teacher->id => 'Teacher'],
            'classes' => [(string) $teacher->id => '3A'],
        ])->assertOk()->assertJsonPath('ok', true);

        $this->postJson('/api/v1/badge_scan/scan', [
            'badge_scan' => $badgeTag,
            'school_year' => self::E2E_SCHOOL_YEAR,
            'semester' => self::E2E_SEMESTER,
        ])->assertOk();

        $this->assertDatabaseHas('scan_log', [
            'user_id' => $teacher->id,
            'card_id' => $badgeTag,
        ]);

        $this->actingAs($admin, 'api');
        $this->getJson('/api/v1/badge_scan/logs')
            ->assertOk()
            ->assertJsonPath('status', true);
    }
}
