/*******************************************************************************
 *
 *    Copyright (c) 2025 - 2026.
 *    Haixing Hu, Qubit Co. Ltd.
 *
 *    All rights reserved.
 *
 ******************************************************************************/
use std::{
    future::Future,
    pin::Pin,
    task::{
        Context,
        Poll,
    },
};

use tokio::task::{
    JoinError,
    JoinHandle,
};

use crate::task::{
    TaskExecutionError,
    TaskResult,
};

/// Async handle returned by Tokio-backed executor services.
///
/// Awaiting this handle reports the accepted task's final result, including
/// task failure, panic, or cancellation.
///
/// # Type Parameters
///
/// * `R` - The task success value.
/// * `E` - The task error value.
///
/// # Author
///
/// Haixing Hu
pub struct TokioTaskHandle<R, E> {
    handle: JoinHandle<TaskResult<R, E>>,
}

impl<R, E> TokioTaskHandle<R, E> {
    /// Creates a handle from a Tokio join handle.
    ///
    /// # Parameters
    ///
    /// * `handle` - The Tokio join handle that resolves to a task result.
    ///
    /// # Returns
    ///
    /// A task handle that can be awaited.
    #[inline]
    pub(crate) fn new(handle: JoinHandle<TaskResult<R, E>>) -> Self {
        Self { handle }
    }

    /// Requests cancellation of the underlying Tokio task.
    ///
    /// # Returns
    ///
    /// `true` after cancellation has been requested.
    #[inline]
    pub fn cancel(&self) -> bool {
        self.handle.abort();
        true
    }

    /// Returns whether the underlying Tokio task has finished.
    ///
    /// # Returns
    ///
    /// `true` if the Tokio task is complete.
    #[inline]
    pub fn is_done(&self) -> bool {
        self.handle.is_finished()
    }
}

impl<R, E> Future for TokioTaskHandle<R, E> {
    type Output = TaskResult<R, E>;

    /// Polls the underlying Tokio task.
    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let this = self.get_mut();
        match Pin::new(&mut this.handle).poll(cx) {
            Poll::Ready(Ok(result)) => Poll::Ready(result),
            Poll::Ready(Err(error)) => Poll::Ready(Err(join_error_to_task_error(error))),
            Poll::Pending => Poll::Pending,
        }
    }
}

/// Converts a Tokio join error into a task execution error.
fn join_error_to_task_error<E>(error: JoinError) -> TaskExecutionError<E> {
    if error.is_cancelled() {
        TaskExecutionError::Cancelled
    } else {
        TaskExecutionError::Panicked
    }
}
