//! Git hooks adapter lowering.

use aqc_text_engine_core::{ItemRequirements, TextFileRequirements};
use shackles_core::{
    AdapterError, EngineRequirementOutput, Provenance, boxed_engine_requirement_for_slot,
};

use crate::types::{ADAPTER_ID, GitHookFileSlot, GitHooksAdapterRequirement};

pub fn lower_git_hooks_requirement(
    provenance: Provenance,
    requirement: GitHooksAdapterRequirement,
) -> Result<EngineRequirementOutput, AdapterError> {
    let (hook, product_id, main_contents, fragment_contents) = requirement.into_parts();
    let main_slot = GitHookFileSlot::main(hook)
        .into_file_slot()
        .map_err(slot_error)?;
    let fragment_slot = GitHookFileSlot::fragment(hook, product_id)
        .into_file_slot()
        .map_err(slot_error)?;
    Ok(vec![
        boxed_engine_requirement_for_slot(
            provenance.clone(),
            main_slot,
            TextFileRequirements {
                exact_contents: None,
                contents: main_contents,
            },
        ),
        boxed_engine_requirement_for_slot(
            provenance,
            fragment_slot,
            TextFileRequirements {
                exact_contents: Some(fragment_contents),
                contents: ItemRequirements::default(),
            },
        ),
    ])
}

fn slot_error(err: shackles_core::FileSlotError) -> AdapterError {
    AdapterError::InvalidRequirement {
        adapter_id: ADAPTER_ID,
        detail: format!("{err:?}"),
    }
}
