-- name: runtimedeploytask__request_action :one
UPDATE runtime_deploy_tasks
SET
    status = 'canceled',
    lease_owner = NULL,
    lease_until = NULL,
    last_error = $5,
    cancel_requested_at = CASE WHEN $2::text = 'cancel' THEN COALESCE(cancel_requested_at, $3::timestamptz) ELSE cancel_requested_at END,
    cancel_requested_by = CASE WHEN $2::text = 'cancel' THEN $4::text ELSE cancel_requested_by END,
    cancel_reason = CASE WHEN $2::text = 'cancel' THEN NULLIF($6::text, '') ELSE cancel_reason END,
    stop_requested_at = CASE WHEN $2::text = 'stop' THEN COALESCE(stop_requested_at, $3::timestamptz) ELSE stop_requested_at END,
    stop_requested_by = CASE WHEN $2::text = 'stop' THEN $4::text ELSE stop_requested_by END,
    stop_reason = CASE WHEN $2::text = 'stop' THEN NULLIF($6::text, '') ELSE stop_reason END,
    terminal_status_source = 'operator',
    terminal_event_seq = terminal_event_seq + 1,
    finished_at = NOW(),
    updated_at = NOW()
WHERE run_id = $1::uuid
RETURNING
    run_id::text AS run_id,
    runtime_mode,
    namespace,
    target_env,
    slot_no,
    repository_full_name,
    services_yaml_path,
    build_ref,
    deploy_only,
    status,
    COALESCE(lease_owner, '') AS lease_owner,
    lease_until,
    attempts,
    COALESCE(last_error, '') AS last_error,
    COALESCE(result_namespace, '') AS result_namespace,
    COALESCE(result_target_env, '') AS result_target_env,
    cancel_requested_at,
    COALESCE(cancel_requested_by, '') AS cancel_requested_by,
    COALESCE(cancel_reason, '') AS cancel_reason,
    stop_requested_at,
    COALESCE(stop_requested_by, '') AS stop_requested_by,
    COALESCE(stop_reason, '') AS stop_reason,
    COALESCE(terminal_status_source, '') AS terminal_status_source,
    terminal_event_seq,
    created_at,
    updated_at,
    started_at,
    finished_at,
    COALESCE(logs_json, '[]'::jsonb) AS logs_json;
