use crate::error::Result;
use crate::state::AppState;
use common_contracts::messages::FetchCompanyDataCommand;
use futures_util::StreamExt;
use tracing::{error, info};

const SUBJECT_NAME: &str = "data_fetch_commands";

pub async fn run(state: AppState) -> Result<()> {
    info!("Starting NATS message consumer...");

    let client = async_nats::connect(&state.config.nats_addr).await?;
    info!("Connected to NATS.");

    // This is a simple subscriber. For production, consider JetStream for durability.
    let mut subscriber = client.subscribe(SUBJECT_NAME.to_string()).await?;

    info!(
        "Consumer started, waiting for messages on subject '{}'",
        SUBJECT_NAME
    );

    while let Some(message) = subscriber.next().await {
        info!("Received NATS message.");
        let state_clone = state.clone();
        let publisher_clone = client.clone();

        tokio::spawn(async move {
            match serde_json::from_slice::<FetchCompanyDataCommand>(&message.payload) {
                Ok(command) => {
                    info!("Deserialized command for symbol: {}", command.symbol);
                    if let Err(e) =
                        crate::worker::handle_fetch_command(state_clone, command, publisher_clone)
                            .await
                    {
                        error!("Error handling fetch command: {:?}", e);
                    }
                }
                Err(e) => {
                    error!("Failed to deserialize message: {}", e);
                }
            }
        });
    }

    Ok(())
}
