use crate::state::RuntimeState;

pub fn runtime_company_highest_live_bond_coupon_rate(
    state: &RuntimeState,
    company_id: u32,
) -> Option<f64> {
    let market_state = state.service_state.company_market_state.get(&company_id)?;
    market_state
        .live_bond_slots
        .iter()
        .filter_map(|slot| {
            let value = f32::from_bits(slot.coupon_rate_raw_u32) as f64;
            value.is_finite().then_some(value)
        })
        .max_by(|left, right| left.partial_cmp(right).unwrap_or(std::cmp::Ordering::Equal))
}

pub fn runtime_company_total_live_bond_principal(
    state: &RuntimeState,
    company_id: u32,
) -> Option<u32> {
    let market_state = state.service_state.company_market_state.get(&company_id)?;
    Some(
        market_state
            .live_bond_slots
            .iter()
            .map(|slot| slot.principal)
            .sum(),
    )
}

pub fn runtime_company_matured_live_bond_count(
    state: &RuntimeState,
    company_id: u32,
    current_year_word: u32,
) -> Option<u32> {
    let market_state = state.service_state.company_market_state.get(&company_id)?;
    Some(
        market_state
            .live_bond_slots
            .iter()
            .filter(|slot| slot.maturity_year != 0 && slot.maturity_year <= current_year_word)
            .count() as u32,
    )
}

pub fn runtime_company_matured_live_bond_principal_total(
    state: &RuntimeState,
    company_id: u32,
    current_year_word: u32,
) -> Option<u32> {
    let market_state = state.service_state.company_market_state.get(&company_id)?;
    Some(
        market_state
            .live_bond_slots
            .iter()
            .filter(|slot| slot.maturity_year != 0 && slot.maturity_year <= current_year_word)
            .map(|slot| slot.principal)
            .sum(),
    )
}

pub fn runtime_company_next_live_bond_maturity_year(
    state: &RuntimeState,
    company_id: u32,
) -> Option<u32> {
    let market_state = state.service_state.company_market_state.get(&company_id)?;
    market_state
        .live_bond_slots
        .iter()
        .filter_map(|slot| (slot.maturity_year != 0).then_some(slot.maturity_year))
        .min()
}
