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

use crate::publications::{sync_pwc_al_publications, PwcAlSyncOptions};
use crate::AppState;

#[derive(Debug, Deserialize, Default)]
pub struct PwcAlSyncBody {
    #[serde(default)]
    pub dry_run: bool,
    #[serde(default)]
    pub include_html: bool,
}

pub async fn post_pwc_al_sync(
    state: web::Data<AppState>,
    body: Option<web::Json<PwcAlSyncBody>>,
) -> HttpResponse {
    let body = body.map(|j| j.into_inner()).unwrap_or_default();
    let opts = PwcAlSyncOptions {
        dry_run: body.dry_run,
        include_html: body.include_html,
    };

    if !opts.dry_run && state.publications.is_none() {
        return HttpResponse::ServiceUnavailable().json(json!({
            "error": "Publications S3 not configured (set S3_PUBLICATIONS_BUCKET and AWS credentials)"
        }));
    }

    let http = reqwest::Client::builder()
        .timeout(std::time::Duration::from_secs(120))
        .build()
        .expect("reqwest client");

    let s3_ref = state.publications.as_deref();
    match sync_pwc_al_publications(&http, s3_ref, &opts).await {
        Ok(result) => HttpResponse::Ok().json(result),
        Err(e) => HttpResponse::BadRequest().json(json!({"error": e.to_string()})),
    }
}
