use crate::{
    commands::{Cli, Config, Result, current_job},
    entities::NaiveDate,
    jobber::JobberCreate,
    print_tip,
};
use clap::Parser;
use color_print::cprintln;

/// Create a new tag
#[derive(Parser, Debug)]
pub(crate) struct CreateInvoice {
    /// job's identifier
    job_id: Option<usize>,
    /// Overall invoice subject
    #[clap(short, long)]
    subject: Option<String>,
    /// Bill until this date
    until: Option<NaiveDate>,
}

impl CreateInvoice {
    pub(crate) fn run(&self, cli: &Cli) -> Result<()> {
        let config = Config::load()?;
        let mut database = cli.open_database()?;
        let job_id = if let Some(job_id) = &self.job_id {
            *job_id
        } else {
            current_job(&config, &database)?
        };
        let invoice_no =
            database.create_invoice([job_id].into_iter(), self.subject.clone(), self.until)?;
        cli.close_database(database)?;
        cprintln!("Successfully created invoice <s>{invoice_no}</> of job <s>{job_id}</>.",);
        print_tip!(cli);
        print_tip!(
            cli,
            "Use <s>jobber show invoice {}</> to take a look.",
            invoice_no
        );
        Ok(())
    }
}
