mod error;
mod handle_id;
mod process;
mod process_handler;
mod shutdown_config;

#[cfg(test)]
mod tests;

use std::{collections::BTreeMap, sync::Arc};

use tokio::sync::Mutex;
use tracing::{debug, info, warn};

pub use error::{BoxError, Error, ProcessFailure, ProcessFailureKind, ProcessResult};
pub use handle_id::HandleID;
pub use process::{Process, ProcessBuilder};
pub use process_handler::ProcessHandler;
pub use shutdown_config::ShutdownConfig;

pub struct ProcessManager {
    inner: Arc<Mutex<Inner>>,
}

impl Default for ProcessManager {
    fn default() -> Self {
        Self::new()
    }
}

impl ProcessManager {
    pub fn new() -> Self {
        debug!("creating process manager");
        Self {
            inner: Arc::new(Mutex::new(Inner::default())),
        }
    }

    pub async fn add_process(&self, process: Process) -> HandleID {
        let handle_id = process.handle_id().clone();
        info!(%handle_id, "adding process to manager");
        self.inner.lock().await.add_process(process);
        handle_id
    }

    pub async fn start_process(&self, handle_id: &HandleID) -> Result<Option<()>, Error> {
        self.inner.lock().await.start_process(handle_id).await
    }

    pub async fn restart_process(&self, handle_id: &HandleID) -> Result<Option<()>, Error> {
        self.inner.lock().await.restart_process(handle_id).await
    }

    pub async fn stop_process(&self, handle_id: &HandleID) -> Result<Option<()>, Error> {
        self.inner.lock().await.stop_process(handle_id).await
    }

    pub async fn kill_process(&self, handle_id: &HandleID) -> Result<Option<()>, Error> {
        self.inner.lock().await.kill_process(handle_id).await
    }
}

#[derive(Default)]
struct Inner {
    handles: BTreeMap<HandleID, Process>,
}

impl Inner {
    fn add_process(&mut self, process: Process) {
        self.handles.insert(process.handle_id().clone(), process);
    }

    async fn start_process(&mut self, handle_id: &HandleID) -> Result<Option<()>, Error> {
        let Some(handle) = self.handles.get_mut(handle_id) else {
            warn!(%handle_id, "process not found");
            return Ok(None);
        };

        handle.start().await?;

        Ok(None)
    }

    async fn restart_process(&mut self, handle_id: &HandleID) -> Result<Option<()>, Error> {
        let Some(handle) = self.handles.get_mut(handle_id) else {
            warn!(%handle_id, "process not found");
            return Ok(None);
        };

        handle.restart().await?;

        Ok(None)
    }

    async fn stop_process(&mut self, handle_id: &HandleID) -> Result<Option<()>, Error> {
        let Some(handle) = self.handles.get_mut(handle_id) else {
            warn!(%handle_id, "process not found");
            return Ok(None);
        };

        handle.stop().await?;

        Ok(None)
    }

    async fn kill_process(&mut self, handle_id: &HandleID) -> Result<Option<()>, Error> {
        let Some(handle) = self.handles.get_mut(handle_id) else {
            warn!(%handle_id, "process not found");
            return Ok(None);
        };

        handle.kill().await?;

        Ok(None)
    }
}
