<?php

/*
|--------------------------------------------------------------------------
| Status Engine
|--------------------------------------------------------------------------
| Central authority for all breakdown lifecycle transitions.
|--------------------------------------------------------------------------
*/

function get_allowed_transitions(): array
{
    return [
        'awaiting_po' => ['broadcasting'],
        'broadcasting' => ['allocated'],
        'allocated' => ['enroute', 'cancelled'],
        'enroute' => ['arrived', 'cancelled'],
        'arrived' => ['in_progress'],
        'in_progress' => ['completed'],
        'completed' => ['archived'],
        'cancelled' => [],
        'archived' => []
    ];
}

function validate_status_transition(array $breakdown, string $new_status): void
{
    if (!empty($breakdown['archived_at'])) {
        json_response(false, 'Archived jobs cannot be modified.', [], 403);
    }

    $current_status = $breakdown['status'];

    $transitions = get_allowed_transitions();

    if (!isset($transitions[$current_status])) {
        json_response(false, 'Invalid current status.', [], 400);
    }

    if (!in_array($new_status, $transitions[$current_status], true)) {
        json_response(false, 'Invalid status transition.', [], 400);
    }
}