//! Integration tests for the `init` subcommand.
//!
//! Covers: initialization without prior setup, with prior setup, and with
//! a `default-scheme` config value that should be applied on init.
//!
//! Requires network access on first run (repos are cached in `tmp/repos/`).

mod utils;

use std::fs;

use crate::utils::{setup, write_to_file, CURRENT_SCHEME_FILE_NAME, REPO_NAME};
use anyhow::{ensure, Result};
use utils::ARTIFACTS_DIR;

#[test]
fn test_cli_init_subcommand_without_setup() -> Result<()> {
    // -------
    // Arrange
    // -------
    let (_, _data_path, command_vec, _temp_dir) =
        setup("test_cli_init_subcommand_without_setup", "init", true)?;
    let expected_output = format!(
        "Failed to initialize, config files seem to be missing. Try applying a theme first with `{REPO_NAME} apply <SCHEME_NAME>`.",
    );

    // ---
    // Act
    // ---
    let (_, stderr) = utils::run_command(&command_vec)?;

    // ------
    // Assert
    // ------
    ensure!(
        stderr.contains(&expected_output),
        "Expected stderr to contain: {expected_output}\nGot: {stderr}"
    );

    Ok(())
}

#[test]
fn test_cli_init_subcommand_with_setup() -> Result<()> {
    // -------
    // Arrange
    // -------
    let (_, _data_path, command_vec, _temp_dir) =
        setup("test_cli_init_subcommand_with_setup", "init", true)?;

    // ---
    // Act
    // ---
    let (stdout, _) = utils::run_command(&command_vec)?;

    // ------
    // Assert
    // ------
    ensure!(stdout.is_empty(), "Expected empty stdout, got: {stdout}");

    Ok(())
}

#[test]
fn test_cli_init_subcommand_with_config_default_scheme() -> Result<()> {
    // -------
    // Arrange
    // -------
    let (config_path, data_path, command_vec, _temp_dir) = setup(
        "test_cli_init_subcommand_with_config_default_scheme",
        "init",
        true,
    )?;
    let scheme_name = "base16-mocha";
    let config_content = format!("default-scheme = \"{scheme_name}\"");
    write_to_file(&config_path, config_content.as_str())?;

    // ---
    // Act
    // ---
    let (stdout, stderr) = utils::run_command(&command_vec)?;

    // ------
    // Assert
    // ------
    let expected_scheme_name =
        fs::read_to_string(data_path.join(ARTIFACTS_DIR).join(CURRENT_SCHEME_FILE_NAME))?;
    ensure!(stdout.is_empty(), "Expected empty stdout, got: {stdout}");
    ensure!(stderr.is_empty(), "Expected empty stderr, got: {stderr}");
    ensure!(
        scheme_name == expected_scheme_name,
        "scheme_name does not contain the expected output"
    );

    Ok(())
}
