use actix_web::{web, HttpResponse, post};
use serde::Deserialize;

#[derive(Debug, Deserialize)]
pub struct SentryEventRequest {
    pub level: Option<String>,
    pub message: String,
    pub stack: Option<String>,
    pub page: Option<String>,
    pub user_id: Option<i32>,
    pub extra: Option<serde_json::Value>,
}

#[post("/api/sentry/events")]
pub async fn report_frontend_error(body: web::Json<SentryEventRequest>) -> HttpResponse {
    let body = body.into_inner();
    tracing::info!("前端错误上报: {}", body.message);

    sentry::with_scope(
        |scope| {
            scope.set_tag("source", "wechat-miniprogram");
            if let Some(page) = &body.page {
                scope.set_tag("page", page);
            }
            if let Some(user_id) = body.user_id {
                scope.set_user(Some(sentry::User {
                    id: Some(user_id.to_string()),
                    ..Default::default()
                }));
            }
            if let Some(extra) = &body.extra {
                if let Some(obj) = extra.as_object() {
                    for (k, v) in obj {
                        scope.set_extra(k, sentry::protocol::Value::from(v.clone()));
                    }
                }
            }
        },
        || {
            sentry::capture_message(&body.message, sentry::Level::Error);
        },
    );

    HttpResponse::Ok().json(serde_json::json!({"success": true}))
}
