use crate::error::MonkError;
use crate::models::Event;

const MAX_BATCH_SIZE: usize = 10_000;

/// Validate a single event before sending it to the API.
pub fn validate_event(event: &Event) -> crate::error::Result<()> {
    if event.event_name.is_empty() {
        return Err(MonkError::Validation("eventName is required".into()));
    }

    match (&event.customer_id, &event.external_customer_id) {
        (None, None) => {
            return Err(MonkError::Validation(
                "exactly one of customerId or externalCustomerId is required".into(),
            ));
        }
        (Some(c), _) if c.is_empty() => {
            return Err(MonkError::Validation(
                "customerId must not be empty when provided".into(),
            ));
        }
        (_, Some(e)) if e.is_empty() => {
            return Err(MonkError::Validation(
                "externalCustomerId must not be empty when provided".into(),
            ));
        }
        _ => {}
    }

    Ok(())
}

/// Validate a batch of events before sending.
pub fn validate_batch(events: &[Event]) -> crate::error::Result<()> {
    if events.is_empty() {
        return Err(MonkError::Validation(
            "events array is required and must not be empty".into(),
        ));
    }

    if events.len() > MAX_BATCH_SIZE {
        return Err(MonkError::Validation(format!(
            "batch size {} exceeds maximum of {MAX_BATCH_SIZE} events",
            events.len()
        )));
    }

    for (i, event) in events.iter().enumerate() {
        if let Err(MonkError::Validation(msg)) = validate_event(event) {
            return Err(MonkError::Validation(format!("event at index {i}: {msg}")));
        }
    }

    Ok(())
}
