use crate::{
    db,
    AppState, ServerError,
};
use axum::{
    extract::{Path, State},
    Json,
    http::StatusCode,
};
use common_contracts::dtos::SessionDataDto;
use service_kit::api;
use uuid::Uuid;
use tracing::info;
use anyhow::Error as AnyhowError;

#[api(POST, "/api/v1/session-data")]
pub async fn insert_session_data(
    State(state): State<AppState>,
    Json(payload): Json<SessionDataDto>,
) -> Result<StatusCode, ServerError> {
    info!(target: "api", request_id = %payload.request_id, provider = %payload.provider, "POST /session-data called");
    db::insert_session_data(&state.pool, &payload).await.map_err(AnyhowError::from)?;
    Ok(StatusCode::CREATED)
}

#[api(GET, "/api/v1/session-data/{request_id}")]
pub async fn get_session_data(
    State(state): State<AppState>,
    Path(request_id): Path<String>,
) -> Result<Json<Vec<SessionDataDto>>, ServerError> {
    let request_id = Uuid::parse_str(&request_id).map_err(|e| AnyhowError::from(e))?;
    info!(target: "api", request_id = %request_id, "GET /session-data/{request_id} called");
    let data = db::get_session_data(&state.pool, request_id).await.map_err(AnyhowError::from)?;
    Ok(Json(data))
}

#[api(DELETE, "/api/v1/session-data/{request_id}")]
pub async fn delete_session_data(
    State(state): State<AppState>,
    Path(request_id): Path<String>,
) -> Result<StatusCode, ServerError> {
    let request_id = Uuid::parse_str(&request_id).map_err(|e| AnyhowError::from(e))?;
    info!(target: "api", request_id = %request_id, "DELETE /session-data/{request_id} called");
    db::delete_session_data(&state.pool, request_id).await.map_err(AnyhowError::from)?;
    Ok(StatusCode::NO_CONTENT)
}

