use crate::authentication::IdentityProviderHandler;
use async_trait::async_trait;
use http_api_isahc_client::IsahcClient;
use oauth2_apple::{AppleProviderWithAppleJs, AppleScope};
use oauth2_client::extensions::{
    AccessTokenResponseSuccessfulBody, Builder, BuilderObtainUserInfoError, BuilderObtainUserInfoOutput, GrantInfo,
};
use oauth2_client::re_exports::{ClientId, ClientSecret, RedirectUri, Scope};
use oauth2_signin::web_app::{SigninFlow, SigninFlowHandleCallbackByQueryConfiguration, SigninFlowHandleCallbackRet};

pub use oauth2_apple;

#[derive(Default)]
pub struct AppleIdentityProviderHandler {}

#[async_trait]
impl IdentityProviderHandler for AppleIdentityProviderHandler {
    async fn handle_callback(
        &self,
        client_id: ClientId,
        client_secret: ClientSecret,
        redirect_uri: RedirectUri,
        query: String,
    ) -> Result<SigninFlowHandleCallbackRet, Box<dyn std::error::Error>> {
        let client = IsahcClient::new()?;
        let provider = AppleProviderWithAppleJs::new(client_id, client_secret, redirect_uri)?;
        let scopes = vec![AppleScope::Email, AppleScope::Name];
        let flow = SigninFlow::new(client, provider, scopes, AppleExtensionsBuilder);
        let config = SigninFlowHandleCallbackByQueryConfiguration::new();
        Ok(flow.handle_callback_by_query(query, config).await)
    }
}

#[derive(Clone, Debug)]
struct AppleExtensionsBuilder;

impl<SCOPE> Builder<SCOPE> for AppleExtensionsBuilder
where
    SCOPE: Scope,
{
    fn obtain_user_info(
        &self,
        _grant_info: GrantInfo<SCOPE>,
        _access_token: &AccessTokenResponseSuccessfulBody<SCOPE>,
    ) -> Result<BuilderObtainUserInfoOutput, BuilderObtainUserInfoError> {
        Ok(BuilderObtainUserInfoOutput::None)
    }
}
