<?php

use App\Enums\WorkAssignmentStatus;
use App\Models\Role;
use App\Models\WorkAssignment;
use App\Services\Works\WorkObservedIncidentsService;

test('resumen incidencias observado cuenta eventos por día en la OT', function () {
    $work = createWorkWithUserAssignments();
    $coord = $work->coordinator;

    WorkAssignment::query()->create([
        'work_id' => $work->id,
        'technician_id' => $work->technician_id,
        'coordinator_id' => $coord?->id,
        'recorded_at' => '2026-05-10 10:00:00',
        'status' => WorkAssignmentStatus::OBSERVADO->value,
    ]);
    WorkAssignment::query()->create([
        'work_id' => $work->id,
        'technician_id' => $work->technician_id,
        'coordinator_id' => $coord?->id,
        'recorded_at' => '2026-05-10 16:00:00',
        'status' => WorkAssignmentStatus::OBSERVADO->value,
    ]);
    WorkAssignment::query()->create([
        'work_id' => $work->id,
        'technician_id' => $work->technician_id,
        'coordinator_id' => $coord?->id,
        'recorded_at' => '2026-05-11 09:00:00',
        'status' => WorkAssignmentStatus::OBSERVADO->value,
    ]);

    $summary = app(WorkObservedIncidentsService::class)->summaryForWork($work->fresh());

    expect($summary->totalEvents)->toBe(3)
        ->and($summary->distinctDays)->toBe(2)
        ->and($summary->countsByDayChronological)->toHaveCount(2)
        ->and($summary->countsByDayChronological[0]['day'])->toBe('2026-05-10')
        ->and($summary->countsByDayChronological[0]['count'])->toBe(2)
        ->and($summary->countsByDayChronological[1]['count'])->toBe(1);
});

test('export incidencias observado exige autenticación', function () {
    $this->get(route('works.export.observed-incidents'))->assertRedirect();
});

test('export incidencias observado responde para coordinador', function () {
    $user = createUserWithRole(Role::COORDINATOR_NAME);

    $this->actingAs($user)
        ->get(route('works.export.observed-incidents'))
        ->assertOk()
        ->assertHeader('content-type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
});

test('export incidencias observado 422 si desde es posterior a hasta', function () {
    $user = createUserWithRole(Role::COORDINATOR_NAME);

    $this->actingAs($user)
        ->get(route('works.export.observed-incidents', ['from' => '2026-06-01', 'to' => '2026-01-01']))
        ->assertStatus(422);
});
