<?php
declare(strict_types=1);
namespace Aen\SerializerWorkshop;

final class Endpoint
{
    public static function handle(string $method, string $contentType, string $body): array
    {
        if($method==='GET')return [200,['status'=>'ready','engine'=>'Symfony Serializer PHP','version'=>Workshop::VERSION,'scenarios'=>Workshop::IDS,'maxRequestBytes'=>32768,'storage'=>false]];
        if($method!=='POST')return [405,['ok'=>false,'code'=>'METHOD_NOT_ALLOWED','message'=>'Используйте POST с JSON.']];
        if(strtolower(trim(explode(';',$contentType)[0]))!=='application/json')return [415,['ok'=>false,'code'=>'JSON_CONTENT_TYPE_REQUIRED','message'=>'Нужен Content-Type: application/json.']];
        if(strlen($body)>32768)return [413,['ok'=>false,'code'=>'REQUEST_TOO_LARGE','message'=>'Запрос должен помещаться в 32 КиБ.']];
        try {
            $request=json_decode($body,false,20,JSON_THROW_ON_ERROR);
            if(!$request instanceof \stdClass || array_diff(array_keys((array)$request),['scenario','input','options']) || !isset($request->scenario,$request->input) || !is_string($request->scenario) || !is_string($request->input))throw new \InvalidArgumentException('INVALID_REQUEST');
            $options=$request->options??new \stdClass();
            if(!$options instanceof \stdClass)throw new \InvalidArgumentException('INVALID_OPTIONS');
            $result=Workshop::run($request->scenario,$request->input,(array)$options);
            return [$result['ok']?200:422,$result];
        }catch(\JsonException $e){return [400,['ok'=>false,'code'=>'INVALID_ENVELOPE_JSON','message'=>'Внешний запрос должен быть корректным JSON.']];}
        catch(\InvalidArgumentException $e){return [400,['ok'=>false,'code'=>$e->getMessage(),'message'=>'Проверьте сценарий, поля запроса и разрешённые настройки.']];}
        catch(\Throwable $e){return [500,['ok'=>false,'code'=>'DEMO_RUNTIME_ERROR','message'=>'Учебный обработчик не смог завершить запрос. Исходники и записанные примеры доступны отдельно.']];}
    }
}
