use sqlx::PgPool;
use crate::{
    models::{BibleVerse, BibleVerseV2},
    error::Result,
    utils::{
        converters::{convert_bible_verses_to_v1, convert_bible_verse_to_v1, convert_bible_verses_to_v2, convert_bible_verse_to_v2},
        db_operations::BibleVerseOperations,
    },
};

/// Bible verse business logic service
/// Contains all bible verse-related business logic, keeping handlers thin and focused on HTTP concerns
pub struct BibleVerseService;

impl BibleVerseService {
    /// Get random bible verse with V1 format (EST timezone)
    pub async fn get_random_v1(pool: &PgPool) -> Result<Option<BibleVerse>> {
        let verse = BibleVerseOperations::get_random(pool).await?;
        
        match verse {
            Some(v) => {
                let converted = convert_bible_verse_to_v1(v)?;
                Ok(Some(converted))
            },
            None => Ok(None),
        }
    }

    /// List all active bible verses with V1 format (EST timezone)
    pub async fn list_v1(pool: &PgPool) -> Result<Vec<BibleVerse>> {
        // Use db module for list since BibleVerseOperations doesn't have it
        let verses = crate::db::bible_verses::list(pool).await?;
        convert_bible_verses_to_v1(verses)
    }

    /// Search bible verses with V1 format (EST timezone)
    pub async fn search_v1(pool: &PgPool, query: &str) -> Result<Vec<BibleVerse>> {
        let verses = BibleVerseOperations::search(pool, query, 100).await?;
        convert_bible_verses_to_v1(verses)
    }

    // V2 API methods (UTC timezone as per shared converter)

    /// Get random bible verse with V2 format (UTC timestamps)
    pub async fn get_random_v2(pool: &PgPool) -> Result<Option<BibleVerseV2>> {
        let verse = BibleVerseOperations::get_random(pool).await?;
        
        match verse {
            Some(v) => {
                let converted = convert_bible_verse_to_v2(v)?;
                Ok(Some(converted))
            },
            None => Ok(None),
        }
    }

    /// List all active bible verses with V2 format (UTC timestamps)
    pub async fn list_v2(pool: &PgPool) -> Result<Vec<BibleVerseV2>> {
        // Use db module for list since BibleVerseOperations doesn't have it
        let verses = crate::db::bible_verses::list(pool).await?;
        convert_bible_verses_to_v2(verses)
    }

    /// Search bible verses with V2 format (UTC timestamps)
    pub async fn search_v2(pool: &PgPool, query: &str) -> Result<Vec<BibleVerseV2>> {
        let verses = BibleVerseOperations::search(pool, query, 100).await?;
        convert_bible_verses_to_v2(verses)
    }
}