<?php

use App\Enums\WorkInternalStatus;
use App\Enums\WorkStatus;
use App\Models\Role;
use App\Support\Works\WorkOperationalEfficiencySnapshot;

test('snapshot null cuando la OT no está finalizada ni cerrada', function () {
    $work = createWorkWithUserAssignments();
    $work->update([
        'work_status' => WorkStatus::ABIERTO->value,
        'internal_status' => WorkInternalStatus::PENDIENTE->value,
    ]);

    expect(WorkOperationalEfficiencySnapshot::forWork($work->fresh()))->toBeNull();
});

test('snapshot calcula ejecución y SLA cumplido', function () {
    $work = createWorkWithUserAssignments();
    $work->update([
        'work_status' => WorkStatus::CERRADO->value,
        'internal_status' => WorkInternalStatus::FINALIZADO->value,
        'scheduled_date' => '2026-05-01 08:00:00',
        'scale_datetime' => '2026-05-01 09:00:00',
        'sla_hours' => 24,
        'clearance_datetime' => '2026-05-01 18:00:00',
    ]);

    $snap = WorkOperationalEfficiencySnapshot::forWork($work->fresh());
    expect($snap)->not->toBeNull();
    expect($snap->executionHours)->toBe(10.0);
    expect($snap->slaMet)->toBeTrue();
    expect($snap->slaMarginHours)->toBeGreaterThan(0);
    // Margen 15 h sobre SLA 24 h → 15/24*100 = 62,5 %
    expect($snap->slaEffectivenessPercent)->toBe(62.5);
});

test('snapshot calcula efectividad SLA cuando no se cumple', function () {
    $work = createWorkWithUserAssignments();
    $work->update([
        'work_status' => WorkStatus::CERRADO->value,
        'internal_status' => WorkInternalStatus::FINALIZADO->value,
        'scheduled_date' => '2026-05-01 08:00:00',
        'scale_datetime' => '2026-05-01 09:00:00',
        'sla_hours' => 24,
        'clearance_datetime' => '2026-05-02 21:00:00',
    ]);

    $snap = WorkOperationalEfficiencySnapshot::forWork($work->fresh());
    expect($snap)->not->toBeNull();
    expect($snap->slaMet)->toBeFalse();
    // Límite 2026-05-02 09:00; clareo 21:00 → retraso 12 h → 100 - 12/24*100 = 50
    expect($snap->slaEffectivenessPercent)->toBe(50.0);
});

test('export eficiencia operativa exige autenticación', function () {
    $this->get(route('works.export.operational'))->assertRedirect();
});

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

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