<?php

declare(strict_types=1);

use App\Models\OperationRun;
use App\Models\SupportRequest;
use App\Models\ManagedEnvironment;
use App\Support\OperationRunOutcome;
use App\Support\OperationRunStatus;
use App\Support\OperationRunType;
use App\Support\SupportRequests\SupportRequestSubmissionService;
use Illuminate\Foundation\Testing\RefreshDatabase;

uses(RefreshDatabase::class);

it('returns the latest tenant-scoped handoff summary without using run-scoped requests', function (): void {
    $tenant = ManagedEnvironment::factory()->create();
    [$user, $tenant] = createUserWithTenant(tenant: $tenant, role: 'owner');

    SupportRequest::factory()->create([
        'workspace_id' => (int) $tenant->workspace_id,
        'managed_environment_id' => (int) $tenant->getKey(),
        'primary_context_type' => SupportRequest::PRIMARY_CONTEXT_TENANT,
        'internal_reference' => 'SR-OLDTENANT0000000000000001',
        'external_handoff_mode' => SupportRequest::EXTERNAL_HANDOFF_MODE_LINK_EXISTING_TICKET,
        'external_ticket_reference' => 'PSA-OLD',
        'created_at' => now()->subMinutes(10),
    ]);

    $run = OperationRun::factory()->create([
        'workspace_id' => (int) $tenant->workspace_id,
        'managed_environment_id' => (int) $tenant->getKey(),
        'type' => OperationRunType::BaselineCompare->value,
        'status' => OperationRunStatus::Completed->value,
        'outcome' => OperationRunOutcome::Failed->value,
        'created_at' => now(),
    ]);

    SupportRequest::factory()
        ->forOperationRun($run)
        ->create([
            'internal_reference' => 'SR-RUN000000000000000000001',
            'external_handoff_mode' => SupportRequest::EXTERNAL_HANDOFF_MODE_LINK_EXISTING_TICKET,
            'external_ticket_reference' => 'PSA-RUN',
            'created_at' => now(),
        ]);

    SupportRequest::factory()->create([
        'workspace_id' => (int) $tenant->workspace_id,
        'managed_environment_id' => (int) $tenant->getKey(),
        'primary_context_type' => SupportRequest::PRIMARY_CONTEXT_TENANT,
        'internal_reference' => 'SR-NEWTENANT0000000000000001',
        'external_handoff_mode' => SupportRequest::EXTERNAL_HANDOFF_MODE_CREATE_EXTERNAL_TICKET,
        'external_handoff_failure_summary' => 'External support desk did not respond before the configured timeout.',
        'created_at' => now()->subMinute(),
    ]);

    $summary = app(SupportRequestSubmissionService::class)->latestTenantHandoffSummary($tenant, $user);

    expect($summary)->not->toBeNull()
        ->and($summary['internal_reference'])->toBe('SR-NEWTENANT0000000000000001')
        ->and($summary['has_failure'])->toBeTrue()
        ->and($summary['has_external_link'])->toBeFalse()
        ->and($summary['external_handoff_failure_summary'])->toContain('configured timeout');
});

it('returns the latest run-scoped handoff summary for the current run only', function (): void {
    $tenant = ManagedEnvironment::factory()->create();
    [$user, $tenant] = createUserWithTenant(tenant: $tenant, role: 'operator');

    $firstRun = OperationRun::factory()->create([
        'workspace_id' => (int) $tenant->workspace_id,
        'managed_environment_id' => (int) $tenant->getKey(),
        'type' => OperationRunType::BaselineCompare->value,
        'status' => OperationRunStatus::Completed->value,
        'outcome' => OperationRunOutcome::Failed->value,
    ]);

    $secondRun = OperationRun::factory()->create([
        'workspace_id' => (int) $tenant->workspace_id,
        'managed_environment_id' => (int) $tenant->getKey(),
        'type' => OperationRunType::BaselineCompare->value,
        'status' => OperationRunStatus::Completed->value,
        'outcome' => OperationRunOutcome::Failed->value,
    ]);

    SupportRequest::factory()
        ->forOperationRun($secondRun)
        ->create([
            'internal_reference' => 'SR-OTHERRUN0000000000000001',
            'external_handoff_mode' => SupportRequest::EXTERNAL_HANDOFF_MODE_LINK_EXISTING_TICKET,
            'external_ticket_reference' => 'PSA-OTHER',
            'created_at' => now(),
        ]);

    SupportRequest::factory()
        ->forOperationRun($firstRun)
        ->create([
            'internal_reference' => 'SR-CURRENTRUN0000000000001',
            'external_handoff_mode' => SupportRequest::EXTERNAL_HANDOFF_MODE_LINK_EXISTING_TICKET,
            'external_ticket_reference' => 'PSA-CURRENT',
            'external_ticket_url' => 'https://desk.example.test/tickets/PSA-CURRENT',
            'created_at' => now()->subMinute(),
        ]);

    $summary = app(SupportRequestSubmissionService::class)->latestOperationRunHandoffSummary($firstRun, $user);

    expect($summary)->not->toBeNull()
        ->and($summary['internal_reference'])->toBe('SR-CURRENTRUN0000000000001')
        ->and($summary['external_ticket_reference'])->toBe('PSA-CURRENT')
        ->and($summary['external_ticket_url'])->toBe('https://desk.example.test/tickets/PSA-CURRENT')
        ->and($summary['has_external_link'])->toBeTrue();
});
