use actix_web::{web, HttpResponse};
use serde::Deserialize;
use serde_json::json;

use crate::data::provider_requests;
use crate::AppState;

#[derive(Debug, Deserialize)]
pub struct ScreenshotRequestBody {
    pub url: String,
    #[serde(default)]
    pub provider_request_id: Option<i64>,
}

pub async fn post_screenshot(
    state: web::Data<AppState>,
    body: web::Json<ScreenshotRequestBody>,
) -> HttpResponse {
    let Some(svc) = state.screenshot.as_ref() else {
        return HttpResponse::ServiceUnavailable().json(json!({
            "error": "Screenshots not configured (set S3_SCREENSHOT_BUCKET and AWS credentials)"
        }));
    };
    let body = body.into_inner();
    if body.url.trim().is_empty() {
        return HttpResponse::BadRequest().json(json!({"error": "url required"}));
    }
    match svc.capture_and_upload_png(body.url.trim()).await {
        Ok(key) => {
            if let (Some(id), Some(cli)) = (body.provider_request_id, state.athena.as_ref()) {
                if let Err(e) = provider_requests::set_screenshot_key(cli, id, &key).await {
                    tracing::warn!("Failed to attach screenshot to provider request {}: {}", id, e);
                }
            }
            HttpResponse::Ok().json(json!({ "s3_key": key }))
        }
        Err(e) => HttpResponse::BadRequest().json(json!({"error": e.to_string()})),
    }
}
