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

final class FacebookProvider extends AbstractProvider
{
    public function id(): string { return 'facebook'; }
    private function version(): string { $v=$this->value('api_version'); return preg_match('/^v\d+\.\d+$/',$v)?$v:'v25.0'; }
    public function authorizationUrl(array $t): string { return $this->query('https://www.facebook.com/'.$this->version().'/dialog/oauth',['client_id'=>$this->value('app_id','FACEBOOK_APP_ID'),'redirect_uri'=>$this->callbackUri(),'response_type'=>'code','scope'=>'public_profile,email','state'=>$t['state']]); }
    public function identity(array $r, array $t): array
    {
        $this->failOnProviderError($r); if (empty($r['code'])) throw new \RuntimeException('Facebook did not return an authorization code.');
        $id=$this->value('app_id','FACEBOOK_APP_ID'); $secret=$this->value('app_secret','FACEBOOK_APP_SECRET'); $base='https://graph.facebook.com/'.$this->version();
        $token=$this->token($base.'/oauth/access_token',['client_id'=>$id,'client_secret'=>$secret,'redirect_uri'=>$this->callbackUri(),'code'=>$r['code']]); $access=(string)($token['access_token']??'');
        $debug=HttpClient::get($base.'/debug_token?'.http_build_query(['input_token'=>$access,'access_token'=>$id.'|'.$secret])); $d=(array)($debug['data']??[]);
        if (empty($d['is_valid']) || (string)($d['app_id']??'')!==$id) throw new \RuntimeException('Facebook access token validation failed.');
        $p=HttpClient::get($base.'/me?'.http_build_query(['fields'=>'id,name,email,picture.type(large)','access_token'=>$access]));
        return ['provider'=>'facebook','subject'=>(string)$p['id'],'email'=>(string)($p['email']??''),'email_verified'=>false,'name'=>(string)($p['name']??''),'picture'=>(string)($p['picture']['data']['url']??''),'raw'=>$p];
    }
}
