use std::path::Path;

use nvlp_core::{crypto, github};

use super::fetch_all_keys;

pub fn handle(
    file: &Path,
    to: &[String],
    description: Option<&str>,
    comment: Option<&str>,
    token: Option<&str>,
) -> anyhow::Result<()> {
    let public_keys = fetch_all_keys(to)?;
    let public_keys: Vec<&str> = public_keys.iter().map(|k| k.as_str()).collect();

    let payload = std::fs::read(file)?;

    let ciphertext_bytes = crypto::encrypt(&payload, &public_keys)?;
    let ciphertext = std::str::from_utf8(&ciphertext_bytes)?;

    let token = github::resolve_token(token)?;

    let mut filename = file
        .file_name()
        .ok_or_else(|| anyhow::anyhow!("invalid file path: {}", file.display()))?
        .to_os_string();
    filename.push(".age");
    let filename = filename.to_string_lossy();

    let recipients = to.join(", @");
    let default_description = format!("nvlp for @{recipients}");
    let description = description.unwrap_or(&default_description);

    let gist = github::create_gist(
        ciphertext,
        &filename,
        &recipients,
        Some(description),
        &token,
    )?;

    for recipient in to {
        github::comment_on_gist(&gist, recipient, comment, &token)?;
    }

    eprintln!("Secret sent to @{recipients}\n{}", gist.html_url);

    Ok(())
}
