use anyhow::Result;
use chrono::Utc;
use clap::{Arg, ArgAction, ArgMatches, Command};

use crate::api::{Api, NewRelease};
use crate::config::Config;
use crate::utils::args::ArgExt as _;

pub fn make_command(command: Command) -> Command {
    command
        .about("Create a new release.")
        .allow_hyphen_values(true)
        .version_arg(false)
        .arg(
            Arg::new("url")
                .long("url")
                .value_name("URL")
                .help("Optional URL to the release for information purposes."),
        )
        .arg(
            Arg::new("finalize")
                .long("finalize")
                .action(ArgAction::SetTrue)
                .help("Immediately finalize the release. (sets it to released)"),
        )
        // Legacy flag that has no effect, left hidden for backward compatibility
        .arg(Arg::new("ref").long("ref").hide(true))
}

pub fn execute(matches: &ArgMatches) -> Result<()> {
    let config = Config::current();
    let api = Api::current();
    #[expect(clippy::unwrap_used, reason = "legacy code")]
    let version = matches.get_one::<String>("version").unwrap();

    api.authenticated()?.new_release(
        &config.get_org(matches)?,
        &NewRelease {
            version: version.to_owned(),
            projects: config.get_projects(matches)?.into(),
            url: matches.get_one::<String>("url").cloned(),
            date_started: Some(Utc::now()),
            date_released: if matches.get_flag("finalize") {
                Some(Utc::now())
            } else {
                None
            },
        },
    )?;

    println!("Created release {version}");
    Ok(())
}
