use crate::authentication::IdentityProviderHandler;
use async_trait::async_trait;
use http_api_isahc_client::IsahcClient;
use oauth2_client::re_exports::{ClientId, ClientSecret, RedirectUri};
use oauth2_signin::web_app::{SigninFlow, SigninFlowHandleCallbackByQueryConfiguration, SigninFlowHandleCallbackRet};
use oauth2_twitter::{TwitterExtensionsBuilder, TwitterProviderWithWebApplication, TwitterScope};

pub use oauth2_twitter;

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

#[async_trait]
impl IdentityProviderHandler for TwitterIdentityProviderHandler {
    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 = TwitterProviderWithWebApplication::new(client_id, client_secret, redirect_uri)?;
        let scopes = vec![TwitterScope::UsersRead];
        let flow = SigninFlow::new(client, provider, scopes, TwitterExtensionsBuilder);
        let config = SigninFlowHandleCallbackByQueryConfiguration::new();
        Ok(flow.handle_callback_by_query(query, config).await)
    }
}
