// Copyright 2024 The Drasi Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::sync::Arc;

use drasi_middleware::map::MapFactory;
use serde_json::json;

use drasi_core::{
    evaluation::{
        context::QueryPartEvaluationContext, functions::FunctionRegistry,
        variable_value::VariableValue,
    },
    middleware::MiddlewareTypeRegistry,
    models::{Element, ElementMetadata, ElementPropertyMap, ElementReference, SourceChange},
    query::QueryBuilder,
};
use drasi_functions_cypher::CypherFunctionSet;
use drasi_query_cypher::CypherParser;

use super::{contains_data, IGNORED_ROW_SIGNATURE};
use crate::QueryTestConfig;

mod queries;

macro_rules! variablemap {
  ($( $key: expr => $val: expr ),*) => {{
       let mut map = ::std::collections::BTreeMap::new();
       $( map.insert($key.to_string().into(), $val); )*
       map
  }}
}

#[allow(clippy::print_stdout, clippy::unwrap_used)]
pub async fn remap(config: &(impl QueryTestConfig + Send)) {
    let mut middleware_registry = MiddlewareTypeRegistry::new();
    middleware_registry.register(Arc::new(MapFactory::new()));
    let middleware_registry = Arc::new(middleware_registry);

    let rm_query = {
        let function_registry = Arc::new(FunctionRegistry::new()).with_cypher_function_set();
        let parser = Arc::new(CypherParser::new(function_registry.clone()));
        let mut builder = QueryBuilder::new(queries::remap_query(), parser)
            .with_function_registry(function_registry);
        builder = config.config_query(builder).await;
        builder = builder.with_middleware_registry(middleware_registry);
        for mw in queries::middlewares() {
            builder = builder.with_source_middleware(mw);
        }
        builder = builder.with_source_pipeline("test", &queries::source_pipeline());
        builder.build().await
    };

    //Add initial value
    {
        let change = SourceChange::Insert {
            element: Element::Node {
                metadata: ElementMetadata {
                    reference: ElementReference::new("test", "t1"),
                    labels: Arc::new([Arc::from("Telemetry")]),
                    effective_from: 0,
                },
                properties: ElementPropertyMap::from(json!({
                    "signals": [
                        {
                            "name": "Vehicle.CurrentLocation.Heading",
                            "value": "96"
                        },
                        {
                            "name": "Vehicle.Speed",
                            "value": "119"
                        },
                        {
                            "name": "Vehicle.TraveledDistance",
                            "value": "4563"
                        }
                    ],
                    "additionalProperties": {
                        "Id": "7dada2cb-a85a-4f38-bc4a-3d74a22c04b0",
                        "Source": "telemetry"
                    },
                    "vehicleId": "v1"
                })),
            },
        };

        let result = rm_query
            .process_source_change(change.clone())
            .await
            .unwrap();
        assert_eq!(result.len(), 1);
        println!("Node Result - Add t1: {result:?}");
        assert!(contains_data(
            &result,
            &QueryPartEvaluationContext::Adding {
                after: variablemap!(
                    "id" => VariableValue::from(json!("v1")),
                    "currentSpeed" => VariableValue::from(json!("119"))
                ),
                row_signature: IGNORED_ROW_SIGNATURE,
            }
        ));
    }

    //Add next value
    {
        let change = SourceChange::Insert {
            element: Element::Node {
                metadata: ElementMetadata {
                    reference: ElementReference::new("test", "t2"),
                    labels: Arc::new([Arc::from("Telemetry")]),
                    effective_from: 0,
                },
                properties: ElementPropertyMap::from(json!({
                    "signals": [
                        {
                            "name": "Vehicle.CurrentLocation.Heading",
                            "value": "98"
                        },
                        {
                            "name": "Vehicle.Speed",
                            "value": "121"
                        },
                        {
                            "name": "Vehicle.TraveledDistance",
                            "value": "4567"
                        }
                    ],
                    "additionalProperties": {
                        "Id": "7dada2cb-a85a-4f38-bc4a-3d74a22c04c2",
                        "Source": "telemetry"
                    },
                    "vehicleId": "v1"
                })),
            },
        };

        let result = rm_query
            .process_source_change(change.clone())
            .await
            .unwrap();
        assert_eq!(result.len(), 1);
        println!("Node Result - Add t2: {result:?}");
        assert!(contains_data(
            &result,
            &QueryPartEvaluationContext::Updating {
                before: variablemap!(
                    "id" => VariableValue::from(json!("v1")),
                    "currentSpeed" => VariableValue::from(json!("119"))
                ),
                after: variablemap!(
                    "id" => VariableValue::from(json!("v1")),
                    "currentSpeed" => VariableValue::from(json!("121"))
                ),
                row_signature: IGNORED_ROW_SIGNATURE,
            }
        ));
    }

    //Add another vehicle
    {
        let change = SourceChange::Insert {
            element: Element::Node {
                metadata: ElementMetadata {
                    reference: ElementReference::new("test", "t3"),
                    labels: Arc::new([Arc::from("Telemetry")]),
                    effective_from: 0,
                },
                properties: ElementPropertyMap::from(json!({
                    "signals": [
                        {
                            "name": "Vehicle.CurrentLocation.Heading",
                            "value": "91"
                        },
                        {
                            "name": "Vehicle.Speed",
                            "value": "110"
                        },
                        {
                            "name": "Vehicle.TraveledDistance",
                            "value": "4063"
                        }
                    ],
                    "additionalProperties": {
                        "Id": "8dada2cb-b85a-4f38-bc4a-3d74a22c04b7",
                        "Source": "telemetry"
                    },
                    "vehicleId": "v2"
                })),
            },
        };

        let result = rm_query
            .process_source_change(change.clone())
            .await
            .unwrap();
        assert_eq!(result.len(), 1);
        println!("Node Result - Add t3: {result:?}");
        assert!(contains_data(
            &result,
            &QueryPartEvaluationContext::Adding {
                after: variablemap!(
                    "id" => VariableValue::from(json!("v2")),
                    "currentSpeed" => VariableValue::from(json!("110"))
                ),
                row_signature: IGNORED_ROW_SIGNATURE,
            }
        ));
    }
}

#[allow(clippy::unwrap_used)]
pub async fn remap_invalid_config_fails(config: &(impl QueryTestConfig + Send)) {
    // Register MapFactory and attempt to build with an invalid selector
    let mut middleware_registry = MiddlewareTypeRegistry::new();
    middleware_registry.register(Arc::new(MapFactory::new()));
    let middleware_registry = Arc::new(middleware_registry);

    let result = {
        let function_registry = Arc::new(FunctionRegistry::new()).with_cypher_function_set();
        let parser = Arc::new(CypherParser::new(function_registry.clone()));
        let mut builder = QueryBuilder::new(queries::remap_query(), parser);
        builder = config.config_query(builder).await;
        builder = builder.with_middleware_registry(middleware_registry);
        for mw in queries::invalid_middlewares() {
            builder = builder.with_source_middleware(mw);
        }
        builder = builder.with_source_pipeline("test", &queries::source_pipeline());
        builder.try_build().await
    };

    assert!(
        result.is_err(),
        "expected invalid map middleware config to fail build"
    );
    let err = result.err().unwrap();
    let err_str = err.to_string();
    assert!(
        err_str.contains("Middleware setup error"),
        "unexpected error: {err_str}"
    );
    assert!(
        err_str.contains("Invalid configuration"),
        "unexpected error: {err_str}"
    );
}

#[allow(clippy::unwrap_used)]
pub async fn remap_incorrect_structure_fails(config: &(impl QueryTestConfig + Send)) {
    // Register MapFactory and attempt to build with incorrect JSON structure
    let mut middleware_registry = MiddlewareTypeRegistry::new();
    middleware_registry.register(Arc::new(MapFactory::new()));
    let middleware_registry = Arc::new(middleware_registry);

    let result = {
        let function_registry = Arc::new(FunctionRegistry::new()).with_cypher_function_set();
        let parser = Arc::new(CypherParser::new(function_registry.clone()));
        let mut builder = QueryBuilder::new(queries::remap_query(), parser);
        builder = config.config_query(builder).await;
        builder = builder.with_middleware_registry(middleware_registry);
        for mw in queries::incorrect_structure_middlewares() {
            builder = builder.with_source_middleware(mw);
        }
        builder = builder.with_source_pipeline("test", &queries::source_pipeline());
        builder.try_build().await
    };

    assert!(
        result.is_err(),
        "expected incorrect map middleware JSON structure to fail build"
    );
    let err = result.err().unwrap();
    let err_str = err.to_string();
    assert!(
        err_str.contains("Middleware setup error"),
        "unexpected error: {err_str}"
    );
    assert!(
        err_str.contains("Invalid configuration"),
        "unexpected error: {err_str}"
    );
}
