/*
 * Copyright (c) 2025, LJason. All Rights Reserved.
 */

use reqwest::RequestBuilder;
use serde::de::DeserializeOwned;

use crate::{BiCoreError, Response};

/// 为 reqwest 请求构建器扩展 Bilibili API 专用发送方法
pub trait BiliRequest {
    /// 发送请求并获取解析后的数据
    #[allow(async_fn_in_trait)]
    async fn core_send<T>(self) -> Result<T, BiCoreError>
    where
        Self: Sized,
        T: DeserializeOwned;
}

impl BiliRequest for RequestBuilder {
    async fn core_send<T>(self) -> Result<T, BiCoreError>
    where
        Self: Sized,
        T: DeserializeOwned,
    {
        // 发送请求
        let response = self.send().await.map_err(|e| BiCoreError::RequestError(e.to_string()))?;

        // 检查状态码
        let status = response.status();
        if !status.is_success() {
            return Err(BiCoreError::RequestError(format!("请求失败: {status}")));
        }

        // 解析数据
        let response = response.json::<Response<T>>().await.map_err(|e| BiCoreError::ParseError(e.to_string()))?;

        // 返回结果
        response.into_result()
    }
}
