<?php
declare(strict_types=1);
namespace PpPhp\Generated\SocialAuth;

final class AppleProvider extends AbstractProvider
{
    public function id(): string { return 'apple'; }
    public function authorizationUrl(array $t): string { return $this->query('https://appleid.apple.com/auth/authorize',['client_id'=>$this->value('services_id','APPLE_SERVICES_ID'),'redirect_uri'=>$this->callbackUri(),'response_type'=>'code id_token','response_mode'=>'form_post','scope'=>'name email','state'=>$t['state'],'nonce'=>$t['nonce']]); }
    public function identity(array $r, array $t): array
    {
        $this->failOnProviderError($r); if (empty($r['code'])) throw new \RuntimeException('Apple did not return an authorization code.');
        $client=$this->value('services_id','APPLE_SERVICES_ID'); $now=time();
        $secret=JwtVerifier::encodeEs256(['alg'=>'ES256','kid'=>$this->value('key_id','APPLE_KEY_ID')],['iss'=>$this->value('team_id','APPLE_TEAM_ID'),'iat'=>$now,'exp'=>$now+300,'aud'=>'https://appleid.apple.com','sub'=>$client],$this->value('private_key','APPLE_PRIVATE_KEY'));
        $tokens=$this->token('https://appleid.apple.com/auth/token',['client_id'=>$client,'client_secret'=>$secret,'code'=>$r['code'],'grant_type'=>'authorization_code','redirect_uri'=>$this->callbackUri()]);
        $c=JwtVerifier::verify((string)($tokens['id_token']??''),'https://appleid.apple.com/auth/keys',['https://appleid.apple.com'],$client,$t['nonce']);
        $user=[]; if (!empty($r['user'])) $user=is_array($r['user'])?$r['user']:(json_decode((string)$r['user'],true)?:[]); $name=trim((string)($user['name']['firstName']??'').' '.(string)($user['name']['lastName']??''));
        return ['provider'=>'apple','subject'=>(string)$c['sub'],'email'=>(string)($c['email']??$user['email']??''),'email_verified'=>$this->verified($c['email_verified']??false),'name'=>$name,'picture'=>'','raw'=>$c];
    }
}
