<?php
namespace EasyChat\Library\Delivery;

use EasyChat\Library\Http\ExternalHttpClient;

 
final class YandexDeliveryTrackingProvider implements TrackingProviderInterface
{
    private const ENDPOINT = 'https://b2b.taxi.yandex.net/b2b/cargo/integration/v2/claims/info';
    private $http; private $token;
    public function __construct($registry, string $token, ?ExternalHttpClient $http = null) { $this->http=$http?:new ExternalHttpClient($registry); $this->token=trim($token); }
    public function code(): string { return 'yandex_delivery'; }
    public function supports(string $carrier, string $number): bool { return (bool)preg_match('/яндекс.*(достав|go)|yandex.*(deliver|go)/ui',$carrier) && (bool)preg_match('/^[a-zA-Z0-9-]{32,64}$/',$number); }
    public function track(string $number): array {
        if ($this->token==='' || !$this->supports('Яндекс Доставка',$number)) return array('status'=>'unavailable');
        $response=$this->http->request('POST',self::ENDPOINT.'?claim_id='.rawurlencode($number),array('headers'=>array('Authorization: Bearer '.$this->token,'Accept'=>'application/json','Accept-Language'=>'ru'),'body'=>'{}','connect_timeout'=>4,'timeout'=>12,'trust_profile'=>'yandex_delivery'));
        if (empty($response['transport_ok'])) return array('status'=>'unavailable'); $code=(int)($response['http_code']??0); if($code===404)return array('status'=>'not_found'); if($code<200||$code>=300)return array('status'=>'unavailable');
        $data=json_decode((string)($response['raw']??''),true); if(!is_array($data))return array('status'=>'unavailable');
        $raw=(string)($data['status']??''); $status=$this->map($raw); $updated=(string)($data['updated_ts']??'');
        return array('status'=>'ready','shipment'=>array('carrier'=>'Яндекс Доставка','carrier_code'=>$this->code(),'tracking_number'=>$number,'status'=>$status,'status_label'=>TrackingStatus::label($status),'updated_at'=>$updated,'tracking_url'=>''),'events'=>array(array('status'=>$status,'label'=>$raw,'date'=>$updated,'location'=>'')));
    }
    public function trackingUrl(string $number): string { return ''; }
    private function map(string $status): string { $status=strtolower($status); if(strpos($status,'delivered')===0)return TrackingStatus::DELIVERED; if(strpos($status,'returned')===0)return TrackingStatus::RETURNED; if(strpos($status,'return')===0)return TrackingStatus::RETURNING; if(strpos($status,'cancel')===0||$status==='failed'||$status==='performer_not_found')return TrackingStatus::PROBLEM; if($status==='delivery_arrived')return TrackingStatus::READY_FOR_PICKUP; if(in_array($status,array('pickuped','performer_found','pickup_arrived'),true))return TrackingStatus::IN_TRANSIT; if($status==='new')return TrackingStatus::CREATED; return TrackingStatus::ACCEPTED; }
}
