//! Error types for the shared API

use axum::{
    http::StatusCode,
    response::{IntoResponse, Response},
    Json,
};
use serde_json::json;
use thiserror::Error;

/// API error type
#[derive(Debug, Error)]
pub enum ApiError {
    /// Not found
    #[error("Not found: {0}")]
    NotFound(String),

    /// Validation error
    #[allow(dead_code)]
    #[error("Validation error: {0}")]
    Validation(String),

    /// Unauthorized (authentication/authorization failure)
    #[error("Unauthorized: {0}")]
    Unauthorized(String),

    /// Internal server error
    #[allow(dead_code)]
    #[error("Internal server error: {0}")]
    Internal(String),

    /// Conflict
    #[allow(dead_code)]
    #[error("Conflict: {0}")]
    Conflict(String),

    /// Database error
    #[error("Database error: {0}")]
    Database(String),
}

impl IntoResponse for ApiError {
    fn into_response(self) -> Response {
        let (status, error_message) = match self {
            ApiError::NotFound(ref msg) => (StatusCode::NOT_FOUND, msg.clone()),
            ApiError::Validation(ref msg) => (StatusCode::BAD_REQUEST, msg.clone()),
            ApiError::Unauthorized(ref msg) => (StatusCode::UNAUTHORIZED, msg.clone()),
            ApiError::Conflict(ref msg) => (StatusCode::CONFLICT, msg.clone()),
            ApiError::Database(_) | ApiError::Internal(_) => (
                StatusCode::INTERNAL_SERVER_ERROR,
                "Internal server error".to_string(),
            ),
        };

        let body = Json(json!({
            "error": error_message,
            "status": status.as_u16(),
        }));

        (status, body).into_response()
    }
}

/// Result type for API operations
pub type ApiResult<T> = Result<T, ApiError>;
