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_microsoft::{MicrosoftExtensionsBuilder, MicrosoftProviderForWebApps, MicrosoftScope, TENANT_COMMON};
use oauth2_signin::web_app::{SigninFlow, SigninFlowHandleCallbackByQueryConfiguration, SigninFlowHandleCallbackRet};

pub use oauth2_microsoft;

pub const MICROSOFT_TENANT: &str = "MICROSOFT_TENANT";

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

#[async_trait]
impl IdentityProviderHandler for MicrosoftIdentityProviderHandler {
    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 tenant = std::env::var(MICROSOFT_TENANT).unwrap_or(TENANT_COMMON.to_string());
        let provider = MicrosoftProviderForWebApps::new(tenant, client_id, client_secret, redirect_uri)?;
        let scopes = vec![MicrosoftScope::Email, MicrosoftScope::Openid];
        let flow = SigninFlow::new(client, provider, scopes, MicrosoftExtensionsBuilder);
        let config = SigninFlowHandleCallbackByQueryConfiguration::new();
        Ok(flow.handle_callback_by_query(query, config).await)
    }
}
