// SHARED PROCESSING FUNCTIONS for bulletins handler
use crate::{
    error::Result, 
    models::Bulletin,
    utils::db_operations::BibleVerseOperations,
};

/// Process multiple bulletins with shared logic
pub async fn process_bulletins_batch(
    pool: &sqlx::PgPool, 
    bulletins: &mut [Bulletin]
) -> Result<()> {
    for bulletin in bulletins.iter_mut() {
        process_single_bulletin(pool, bulletin).await?;
    }
    Ok(())
}

/// Process a single bulletin with all required transformations
pub async fn process_single_bulletin(
    pool: &sqlx::PgPool, 
    bulletin: &mut Bulletin
) -> Result<()> {
    // Process scripture reading to include full verse text
    bulletin.scripture_reading = process_scripture_reading(pool, &bulletin.scripture_reading).await?;
    
    // Process hymn references in worship content - stub for now
    // if let Some(ref worship_content) = bulletin.divine_worship {
    //     bulletin.divine_worship = Some(super::bulletins::process_hymn_references(pool, worship_content).await?);
    // }
    
    // Process hymn references in sabbath school content - stub for now
    // if let Some(ref ss_content) = bulletin.sabbath_school {
    //     bulletin.sabbath_school = Some(super::bulletins::process_hymn_references(pool, ss_content).await?);
    // }
    
    // Ensure sunset field compatibility
    if bulletin.sunset.is_none() {
        bulletin.sunset = Some("TBA".to_string());
    }
    
    Ok(())
}

/// Process scripture reading field to lookup and include full verse text
async fn process_scripture_reading(
    pool: &sqlx::PgPool,
    scripture: &Option<String>,
) -> Result<Option<String>> {
    let Some(scripture_text) = scripture else {
        return Ok(None);
    };

    // If it already looks like it has full verse text (long), return as-is
    if scripture_text.len() > 50 {
        return Ok(Some(scripture_text.clone()));
    }

    // Try to find the verse using existing search functionality
    match BibleVerseOperations::search(pool, scripture_text, 1).await {
        Ok(verses) if !verses.is_empty() => {
            let verse = &verses[0];
            // Put verse text first, then reference at the end
            Ok(Some(format!("{} - {}", verse.text, scripture_text)))
        },
        _ => {
            // If no match found, return original text
            Ok(Some(scripture_text.clone()))
        }
    }
}