use duroxide::providers::ProviderError;

/// Map an HTTP status code and message from CosmosDB into a ProviderError.
pub fn map_cosmosdb_error(operation: &str, status: u16, message: &str) -> ProviderError {
    match status {
        // Conflict — ETag mismatch or duplicate ID
        409 => ProviderError::retryable(operation, format!("CosmosDB conflict (409): {message}")),
        // Too many requests — rate limited
        429 => {
            ProviderError::retryable(operation, format!("CosmosDB rate limited (429): {message}"))
        }
        // Request timeout
        408 => ProviderError::retryable(
            operation,
            format!("CosmosDB request timeout (408): {message}"),
        ),
        // Precondition failed — ETag mismatch on conditional write
        412 => ProviderError::retryable(
            operation,
            format!("CosmosDB precondition failed (412): {message}"),
        ),
        // Service unavailable
        503 => ProviderError::retryable(
            operation,
            format!("CosmosDB service unavailable (503): {message}"),
        ),
        // Not found
        404 => ProviderError::permanent(operation, format!("CosmosDB not found (404): {message}")),
        // Bad request
        400 => {
            ProviderError::permanent(operation, format!("CosmosDB bad request (400): {message}"))
        }
        // Request entity too large
        413 => ProviderError::permanent(
            operation,
            format!("CosmosDB request too large (413): {message}"),
        ),
        // Other errors: assume transient for 5xx, permanent for 4xx
        s if s >= 500 => {
            ProviderError::retryable(operation, format!("CosmosDB server error ({s}): {message}"))
        }
        s => ProviderError::permanent(operation, format!("CosmosDB client error ({s}): {message}")),
    }
}

/// Check if an HTTP status represents a conflict (409).
pub fn is_conflict(status: u16) -> bool {
    status == 409
}

/// Check if an HTTP status represents not found (404).
pub fn is_not_found(status: u16) -> bool {
    status == 404
}

/// Check if an HTTP status represents precondition failed (412).
pub fn is_precondition_failed(status: u16) -> bool {
    status == 412
}
