<?php
require_once __DIR__.'/../tracking.php';
emsListenerHeaders();header('Content-Type: application/json');
try{
    $secret=(string)getenv('TRACKING_TOKEN_V2_REGISTER_BEARER');$supplied=(string)($_SERVER['HTTP_AUTHORIZATION']??'');
    $host=emsListenerHost();$registered=false;foreach(emsTrackingConfig()['accounts'] as $p)if($p['tracking_host']===$host)$registered=true;
    if(!$registered||strlen($secret)<43||strlen($secret)>256||!hash_equals('Bearer '.$secret,$supplied)){http_response_code(401);echo '{"error":"unauthorized"}';return;}
    if(($_SERVER['REQUEST_METHOD']??'')==='GET'){echo json_encode(emsTokenV2Readiness(emsTokenV2ListenerDb(),'listener'),JSON_THROW_ON_ERROR);return;}
    if(($_SERVER['REQUEST_METHOD']??'')!=='POST'){header('Allow: GET, POST');http_response_code(405);return;}
    $body=file_get_contents('php://input',false,null,0,524289);
    if(strlen($body)>524288)throw new RuntimeException('v2_batch_too_large');$data=json_decode($body,true,12,JSON_THROW_ON_ERROR);
    if(($data['protocol']??'')!=='v2'||($data['schema']??null)!==EMS_TOKEN_V2_SCHEMA){
        emsTokenV2Diagnostic('V2_PROTOCOL_MISMATCH');throw new RuntimeException('v2_protocol_mismatch');}
    if(!is_array($data['records']??null)||!array_is_list($data['records'])||!$data['records']||count($data['records'])>EMS_TOKEN_V2_MAX_RECORDS)throw new RuntimeException('v2_batch_invalid');
    foreach($data['records'] as $r){
        $r=emsTokenV2Record($r);if($r['stream_id']!==emsTrackingConfig()['stream_id'])throw new RuntimeException('v2_stream_mismatch');
        $known=false;foreach(emsTrackingConfig()['accounts'] as $p)if($p['tracking_host']===$r['host'])$known=true;
        if(!$known)throw new RuntimeException('v2_host_unregistered');
        if($r['purpose']==='unsubscribe')emsTokenV2Evidence($r); // Fail registration if event signing is not commissioned.
    }
    $db=emsTokenV2ListenerDb();$s=$db->prepare('SELECT last_id FROM tracking_optout_stream WHERE stream_id=?');$s->execute([emsTrackingConfig()['stream_id']]);
    if($s->fetchColumn()===false)throw new RuntimeException('v2_stream_unavailable');
    echo json_encode((new EmsTokenV2Registry($db))->register($data['records']),JSON_THROW_ON_ERROR);
}catch(Throwable $e){emsTokenV2Diagnostic('V2_TOKEN_REGISTRATION_FAILED');http_response_code(503);echo '{"error":"v2_registration_unavailable"}';}
