use clap::Parser;
use jwt_simple::algorithms::HS256Key;
use jwt_simple::prelude::{Clock, Duration, JWTClaims, MACLike};
use moneymgr_backend::constants;
use moneymgr_backend::extractors::auth_extractor::TokenClaims;
use moneymgr_backend::utils::rand_utils::rand_string;
use std::ops::Add;
use std::os::unix::prelude::CommandExt;
use std::process::Command;

/// cURL wrapper to query Money manager
#[derive(Parser, Debug)]
#[command(version, about, long_about = None)]
struct Args {
    /// URL to Money manager API
    #[arg(short('U'), long, env, default_value = "http://localhost:8000/api")]
    moneymgr_url: String,

    /// Token ID
    #[arg(short('i'), long, env)]
    token_id: u32,

    /// Token secret
    #[arg(short('t'), long, env)]
    token_secret: String,

    /// Request verb
    #[arg(short('X'), long, default_value = "GET")]
    method: String,

    /// Request URI
    uri: String,

    /// Command line arguments to pass to cURL
    #[clap(trailing_var_arg = true, allow_hyphen_values = true)]
    run: Vec<String>,
}

fn main() {
    let args: Args = Args::parse();

    let full_url = format!("{}{}", args.moneymgr_url, args.uri);

    log::debug!("Full URL: {full_url}");

    let key = HS256Key::from_bytes(args.token_secret.as_bytes());

    let claims = JWTClaims::<TokenClaims> {
        issued_at: Some(Clock::now_since_epoch()),
        expires_at: Some(Clock::now_since_epoch().add(Duration::from_mins(15))),
        invalid_before: None,
        issuer: None,
        subject: None,
        audiences: None,
        jwt_id: None,
        nonce: Some(rand_string(10)),
        custom: TokenClaims {
            method: args.method.to_string(),
            uri: args.uri,
        },
    };

    let jwt = key
        .with_key_id(&args.token_id.to_string())
        .authenticate(claims)
        .expect("Failed to sign JWT!");

    let _ = Command::new("curl")
        .args(["-X", &args.method])
        .args(["-H", &format!("{}: {jwt}", constants::API_TOKEN_HEADER)])
        .args(args.run)
        .arg(full_url)
        .exec();

    panic!("Failed to run cURL!")
}
