use std::io;

use mangadex_api::v2::MangaDexV2;
use mangadex_api::web_scrape::responses::LoginAjaxResponseType;

#[tokio::main]
async fn main() -> Result<(), reqwest::Error> {
    let mangadex_client = MangaDexV2::default();

    let mut username = String::new();
    println!("Enter your MangaDex username:");
    io::stdin()
        .read_line(&mut username)
        .expect("Failed to read username");

    let mut password = String::new();
    println!("Enter your MangaDex password:");
    io::stdin()
        .read_line(&mut password)
        .expect("Failed to read password");

    // If you know that you need a 2-factor authentication code, you can add it directly before
    // sending the first login attempt and not check the `TwoFactorAuthenticationRequired` variant.
    match mangadex_client
        .login_ajax(&username, &password)
        .send()
        .await?
    {
        LoginAjaxResponseType::Ok => {
            println!("Login successful!")
        }
        LoginAjaxResponseType::TwoFactorAuthenticationRequired => {
            let mut two_factor = String::new();
            loop {
                println!("Enter your 2FA code:");
                io::stdin()
                    .read_line(&mut two_factor)
                    .expect("Failed to read 2FA code");

                match mangadex_client
                    .login_ajax(&username, &password)
                    .two_factor(&two_factor)
                    .send()
                    .await?
                {
                    LoginAjaxResponseType::Ok => {
                        println!("Login successful!");
                        break;
                    }
                    LoginAjaxResponseType::IncorrectTwoFactorCodeLength
                    | LoginAjaxResponseType::FailedTwoFactorVerification => {
                        println!("Incorrect 2FA code")
                    }
                    _ => panic!("There was an error submitting the 2FA code"),
                }
            }
        }
        _ => panic!("There was an error logging in."),
    }

    Ok(())
}
