use actix_web::{HttpResponse, web};
use serde::Serialize;
use service::{
    AppService, Pagination,
    user::notification::{
        AppNotificationItem, UpdateUserNotificationConfig,
        UserNotificationConfig,
    },
};
use session::Session;

use crate::error::ApiError;

fn ok_json<T: Serialize>(data: T) -> Result<HttpResponse, ApiError> {
    Ok(HttpResponse::Ok().json(data))
}

#[utoipa::path(
    get,
    path = "/api/v1/user/notifications",
    params(Pagination),
    responses(
        (status = 200, body = Vec<AppNotificationItem>)
    ),
    tag = "user"
)]
pub async fn list_notifications(
    service: web::Data<AppService>,
    session: Session,
    query: web::Query<Pagination>,
) -> Result<HttpResponse, ApiError> {
    let notifications = service
        .list_notifications(&session, query.into_inner())
        .await?;
    ok_json(notifications)
}

#[utoipa::path(
    put,
    path = "/api/v1/user/config/notification",
    request_body = UpdateUserNotificationConfig,
    responses(
        (status = 200, body = UserNotificationConfig)
    ),
    tag = "user"
)]
pub async fn update_notification(
    service: web::Data<AppService>,
    session: Session,
    body: web::Json<UpdateUserNotificationConfig>,
) -> Result<HttpResponse, ApiError> {
    let config = service
        .user_update_notification_config(&session, body.into_inner())
        .await?;
    ok_json(config)
}
