use crate::provider::Provider;
use crate::user::ConnectUser;
use async_trait::async_trait;
use base64::Engine;
use jsonwebtoken::{Algorithm, EncodingKey, Header, encode};
use reqwest::Client;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::sync::OnceLock;
use std::time::{SystemTime, UNIX_EPOCH};

static CLIENT: OnceLock<Client> = OnceLock::new();

pub struct AppleProvider {
    client_id: String,
    team_id: String,
    key_id: String,
    private_key_pem: String,
    redirect_url: String,
    http_client: Client,
    scopes: Vec<String>,
    state: Option<String>,
    pkce_challenge: Option<String>,
}

#[derive(Debug, Serialize, Deserialize)]
struct AppleClaims {
    iss: String,
    iat: u64,
    exp: u64,
    aud: String,
    sub: String,
}

impl AppleProvider {
    /// Apple requires a Team ID, a Key ID, and the contents of a .p8 Private Key file
    /// to dynamically generate the client_secret JWT on every login.
    pub fn new(
        client_id: String,
        team_id: String,
        key_id: String,
        private_key_pem: String,
        redirect_url: String,
    ) -> Self {
        Self {
            client_id,
            team_id,
            key_id,
            private_key_pem,
            redirect_url,
            http_client: CLIENT.get_or_init(Client::new).clone(),
            scopes: vec!["name".to_string(), "email".to_string()],
            state: None,
            pkce_challenge: None,
        }
    }

    pub fn with_scopes(mut self, scopes: &[&str]) -> Self {
        self.scopes = scopes.iter().map(|s: &&str| s.to_string()).collect();
        self
    }

    pub fn with_state(mut self, state: &str) -> Self {
        self.state = Some(state.to_string());
        self
    }

    pub fn with_pkce(mut self, challenge: &str) -> Self {
        self.pkce_challenge = Some(challenge.to_string());
        self
    }

    fn generate_client_secret(&self) -> Result<String, crate::error::ConnectError> {
        let now = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs();
        let claims = AppleClaims {
            iss: self.team_id.clone(),
            iat: now,
            exp: now + 86400 * 30, // 30 days expiration
            aud: "https://appleid.apple.com".to_string(),
            sub: self.client_id.clone(),
        };

        let mut header = Header::new(Algorithm::ES256);
        header.kid = Some(self.key_id.clone());

        let encoding_key = EncodingKey::from_ec_pem(self.private_key_pem.as_bytes())?;
        let token = encode(&header, &claims, &encoding_key)?;

        Ok(token)
    }
}

#[async_trait]
impl Provider for AppleProvider {
    fn redirect_url(&self) -> String {
        let mut params = crate::provider::build_oauth_params(
            &self.client_id,
            &self.redirect_url,
            &self.scopes,
            self.state.as_deref(),
            self.pkce_challenge.as_deref(),
        );
        params.append_pair("response_type", "code");
        params.append_pair("response_mode", "form_post");
        format!(
            "https://appleid.apple.com/auth/authorize?{}",
            params.finish()
        )
    }

    async fn get_user(&self, auth_code: &str) -> Result<ConnectUser, crate::error::ConnectError> {
        let client_secret = self.generate_client_secret()?;

        let token_res = self
            .http_client
            .post(self.token_url())
            .form(&[
                ("client_id", self.client_id.as_str()),
                ("client_secret", client_secret.as_str()),
                ("code", auth_code),
                ("grant_type", "authorization_code"),
                ("redirect_uri", self.redirect_url.as_str()),
            ])
            .send()
            .await?
            .error_for_status()?
            .json::<Value>()
            .await?;

        // Apple returns user data inside an "id_token" (JWT)
        let id_token_str = token_res["id_token"].as_str().ok_or_else(|| {
            crate::error::ConnectError::Token("Failed to get id_token from Apple".to_string())
        })?;
        let access_token = token_res["access_token"].as_str().unwrap_or("").to_string();

        let mut user = self.get_user_from_token(id_token_str).await?;
        user.access_token = access_token;
        user.refresh_token = token_res["refresh_token"]
            .as_str()
            .map(|s: &str| s.to_string());
        user.expires_in = token_res["expires_in"]
            .as_u64()
            .or_else(|| token_res["expires_in"].as_i64().map(|v| v as u64));
        Ok(user)
    }

    /// For Apple, `access_token` parameter should actually be the `id_token` JWT string.
    async fn get_user_from_token(
        &self,
        id_token_str: &str,
    ) -> Result<ConnectUser, crate::error::ConnectError> {
        let parts: Vec<&str> = id_token_str.split('.').collect();
        if parts.len() != 3 {
            return Err(crate::error::ConnectError::Provider(
                "Invalid id_token format".to_string(),
            ));
        }

        let payload_bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD.decode(parts[1])?;
        let payload: Value = serde_json::from_slice(&payload_bytes)?;

        Ok(ConnectUser {
            id: payload["sub"].as_str().unwrap_or("").to_string(),
            name: String::with_capacity(256), // Developer needs to extract this from the form_post on first login
            email: payload["email"].as_str().map(|s: &str| s.to_string()),
            avatar_url: None, // Apple does not provide avatars
            email_verified: None,
            raw_data: payload,
            access_token: id_token_str.to_string(),
            refresh_token: None,
            expires_in: None,
        })
    }

    fn token_url(&self) -> String {
        "https://appleid.apple.com/auth/token".to_string()
    }

    async fn refresh_token(
        &self,
        refresh_token: &str,
    ) -> Result<ConnectUser, crate::error::ConnectError> {
        let client_secret = self.generate_client_secret()?;

        let token_res = self
            .http_client
            .post(self.token_url())
            .form(&[
                ("client_id", self.client_id.as_str()),
                ("client_secret", client_secret.as_str()),
                ("refresh_token", refresh_token),
                ("grant_type", "refresh_token"),
            ])
            .send()
            .await?
            .error_for_status()?
            .json::<serde_json::Value>()
            .await?;

        if let Some(err) = token_res["error"].as_str() {
            let err_desc = token_res["error_description"].as_str().unwrap_or("");
            return Err(crate::error::ConnectError::Token(format!(
                "Provider returned error: {} - {}",
                err, err_desc
            )));
        }

        let access_token = token_res["access_token"].as_str().ok_or_else(|| {
            crate::error::ConnectError::Token(
                "Failed to get access_token during refresh".to_string(),
            )
        })?;

        let mut user = self.get_user_from_token(access_token).await?;
        user.refresh_token = token_res["refresh_token"].as_str().map(|s| s.to_string());
        user.expires_in = token_res["expires_in"]
            .as_u64()
            .or_else(|| token_res["expires_in"].as_i64().map(|v| v as u64));
        Ok(user)
    }
}
