// Copyright (c) Subzero Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

use std::fmt;

use borsh::{BorshDeserialize, BorshSerialize};
use serde::{Deserialize, Serialize};

/// Filter to apply to HTTP GET responses from REX requests.
///
/// This enum allows filtering the raw response data from HTTP GET REX requests
/// using either regex patterns or JSONPath expressions.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, BorshSerialize, BorshDeserialize)]
pub enum HttpFilter {
    /// Filter using a regex pattern
    Regex(String),
    /// Filter using a JSONPath expression
    JsonPath(String),
}

impl std::str::FromStr for HttpFilter {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if let Some(rest) = s.strip_prefix("regex:") {
            Ok(HttpFilter::Regex(rest.to_string()))
        } else if let Some(rest) = s.strip_prefix("jsonpath:") {
            Ok(HttpFilter::JsonPath(rest.to_string()))
        } else {
            Err(
                "Invalid HttpGetFilter format. Use 'regex:<pattern>' or 'jsonpath:<expr>'."
                    .to_string(),
            )
        }
    }
}

impl fmt::Display for HttpFilter {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            HttpFilter::Regex(s) => write!(f, "regex:{s}"),
            HttpFilter::JsonPath(s) => write!(f, "jsonpath:{s}"),
        }
    }
}
