use actix_web::{post, web, HttpRequest, HttpResponse, Responder};
use crate::security::jwt::JwtManager;
use crate::core::sensors_analyzer::SensorReading;
use crate::AppState;
use serde::Deserialize;
#[derive(Deserialize)]
pub struct SensorsAnalyzeRequest {
pub reading: SensorReading, pub history: Vec<SensorReading>, }
#[post("/sensors/analyze")]
pub async fn analyze_sensors(
req: HttpRequest, payload: web::Json<SensorsAnalyzeRequest> ) -> impl Responder {
let token = match req.headers().get("Authorization") {
Some(hv) => hv.to_str().unwrap_or("").replace("Bearer ", ""),
None => String::new(),
};
if token.is_empty() {
return HttpResponse::Unauthorized().body("Missing Authorization token");
}
let jwt_manager = JwtManager::new(
secrecy::Secret::new("a_very_secure_and_long_secret_key_that_is_at_least_32_bytes_long".to_string()),
60,
"my_app".to_string(),
"user_service".to_string(),
);
match jwt_manager.decode_token(&token) {
Ok(_) => {},
Err(_) => return HttpResponse::Unauthorized().body("Invalid or expired token"),
};
let engine = &req.app_data::<web::Data<AppState>>().unwrap().x_engine.sensors_engine;
match engine.analyze(payload.reading.clone(), &payload.history).await {
Ok(result) => HttpResponse::Ok().json(result), Err(e) => HttpResponse::InternalServerError().json(e.to_string()), }
}