use crate::{ApiResponse, error::ApiError};
use actix_web::{HttpResponse, Result, web};
use service::AppService;
use service::agent::model::{CreateModelRequest, UpdateModelRequest};
use session::Session;
use uuid::Uuid;

#[derive(serde::Deserialize, utoipa::IntoParams)]
pub struct ListQuery {
    pub provider_id: Option<String>,
}

#[utoipa::path(
    get,
    path = "/api/agents/models",
    params(ListQuery),
    responses(
        (status = 200, body = Vec<service::agent::model::ModelResponse>),
        (status = 401, description = "Unauthorized"),
    ),
    tag = "Agent"
)]
pub async fn model_list(
    service: web::Data<AppService>,
    session: Session,
    query: web::Query<ListQuery>,
) -> Result<HttpResponse, ApiError> {
    let provider_id = if let Some(ref s) = query.provider_id {
        Some(Uuid::parse_str(s).map_err(|_| {
            service::error::AppError::BadRequest("Invalid provider UUID".to_string())
        })?)
    } else {
        None
    };
    let resp = service.agent_model_list(provider_id, &session).await?;
    Ok(ApiResponse::ok(resp).to_response())
}

#[utoipa::path(
    get,
    path = "/api/agents/models/{id}",
    params(("id" = String, Path)),
    responses(
        (status = 200, body = service::agent::model::ModelResponse),
        (status = 401, description = "Unauthorized"),
        (status = 404),
    ),
    tag = "Agent"
)]
pub async fn model_get(
    service: web::Data<AppService>,
    session: Session,
    path: web::Path<String>,
) -> Result<HttpResponse, ApiError> {
    let id = Uuid::parse_str(&path.into_inner())
        .map_err(|_| service::error::AppError::BadRequest("Invalid UUID".to_string()))?;
    let resp = service.agent_model_get(id, &session).await?;
    Ok(ApiResponse::ok(resp).to_response())
}

#[utoipa::path(
    post,
    path = "/api/agents/models",
    request_body = CreateModelRequest,
    responses(
        (status = 200, body = service::agent::model::ModelResponse),
        (status = 401),
        (status = 403),
        (status = 404),
    ),
    tag = "Agent"
)]
pub async fn model_create(
    service: web::Data<AppService>,
    session: Session,
    body: web::Json<CreateModelRequest>,
) -> Result<HttpResponse, ApiError> {
    let resp = service
        .agent_model_create(body.into_inner(), &session)
        .await?;
    Ok(ApiResponse::ok(resp).to_response())
}

#[utoipa::path(
    patch,
    path = "/api/agents/models/{id}",
    params(("id" = String, Path)),
    request_body = UpdateModelRequest,
    responses(
        (status = 200, body = service::agent::model::ModelResponse),
        (status = 401),
        (status = 403),
        (status = 404),
    ),
    tag = "Agent"
)]
pub async fn model_update(
    service: web::Data<AppService>,
    session: Session,
    path: web::Path<String>,
    body: web::Json<UpdateModelRequest>,
) -> Result<HttpResponse, ApiError> {
    let id = Uuid::parse_str(&path.into_inner())
        .map_err(|_| service::error::AppError::BadRequest("Invalid UUID".to_string()))?;
    let resp = service
        .agent_model_update(id, body.into_inner(), &session)
        .await?;
    Ok(ApiResponse::ok(resp).to_response())
}

#[utoipa::path(
    delete,
    path = "/api/agents/models/{id}",
    params(("id" = String, Path)),
    responses(
        (status = 200),
        (status = 401),
        (status = 403),
        (status = 404),
    ),
    tag = "Agent"
)]
pub async fn model_delete(
    service: web::Data<AppService>,
    session: Session,
    path: web::Path<String>,
) -> Result<HttpResponse, ApiError> {
    let id = Uuid::parse_str(&path.into_inner())
        .map_err(|_| service::error::AppError::BadRequest("Invalid UUID".to_string()))?;
    service.agent_model_delete(id, &session).await?;
    Ok(crate::api_success())
}
