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

/// Cancel any running work.
///
/// This function can be undone with `jobber undo`.
#[derive(Parser, Debug)]
pub(crate) struct Cancel {
    /// ID of the job to end work for (default is current job).
    #[clap(short, long)]
    job: Option<usize>,
}

impl Cancel {
    pub(crate) fn run(&self, cli: &Cli) -> Result<()> {
        let config = Config::load()?;
        let mut database = cli.open_database()?;
        let job_id = self.job.unwrap_or(current_job(&config, &database)?);
        database.cancel_work(job_id)?;
        cli.close_database(database)?;
        cprintln!("Successfully canceled work in job {job_id}");
        if !cli.no_tips {
            print_tip!(cli);
            print_tip!(cli, "Use <s>jobber undo</> to undo cancellation.");
        }
        Ok(())
    }
}
