// Copyright 2025 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.

#![allow(clippy::unwrap_used)]
use std::sync::Arc;

use serde_json::json;

use drasi_core::{
    evaluation::{
        context::QueryPartEvaluationContext, functions::FunctionRegistry,
        variable_value::VariableValue,
    },
    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
  }}
}

pub async fn prev_unique(config: &(impl QueryTestConfig + Send)) {
    let opt_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::prev_distinct_query(), parser)
            .with_function_registry(function_registry);
        builder = config.config_query(builder).await;
        builder.build().await
    };

    //Add contract 1
    {
        let change = SourceChange::Insert {
            element: Element::Node {
                metadata: ElementMetadata {
                    reference: ElementReference::new("test", "c1"),
                    labels: Arc::new([Arc::from("Contract")]),
                    effective_from: 0,
                },
                properties: ElementPropertyMap::from(json!({
                    "id": "c1",
                    "status": "pending",
                    "tags": "tag1"
                })),
            },
        };

        let result = opt_query
            .process_source_change(change.clone())
            .await
            .unwrap();
        assert_eq!(result.len(), 0);
    }

    //update contract 1 with active status
    {
        let change = SourceChange::Update {
            element: Element::Node {
                metadata: ElementMetadata {
                    reference: ElementReference::new("test", "c1"),
                    labels: Arc::new([Arc::from("Contract")]),
                    effective_from: 0,
                },
                properties: ElementPropertyMap::from(json!({
                    "id": "c1",
                    "status": "active",
                    "tags": "tag1"
                })),
            },
        };

        let result = opt_query
            .process_source_change(change.clone())
            .await
            .unwrap();

        assert_eq!(result.len(), 1);

        assert!(contains_data(
            &result,
            &QueryPartEvaluationContext::Adding {
                after: variablemap!(
                  "tags" => VariableValue::from(json!("tag1")),
                  "status" => VariableValue::from(json!("active")),
                  "id" => VariableValue::from(json!("c1"))
                ),
                row_signature: IGNORED_ROW_SIGNATURE,
            }
        ));
    }

    //update contract 1 tags
    {
        let change = SourceChange::Update {
            element: Element::Node {
                metadata: ElementMetadata {
                    reference: ElementReference::new("test", "c1"),
                    labels: Arc::new([Arc::from("Contract")]),
                    effective_from: 0,
                },
                properties: ElementPropertyMap::from(json!({
                    "id": "c1",
                    "status": "active",
                    "tags": "tag2"
                })),
            },
        };

        let result = opt_query
            .process_source_change(change.clone())
            .await
            .unwrap();

        assert_eq!(result.len(), 1);

        assert!(contains_data(
            &result,
            &QueryPartEvaluationContext::Updating {
                before: variablemap!(
                  "tags" => VariableValue::from(json!("tag1")),
                  "status" => VariableValue::from(json!("active")),
                  "id" => VariableValue::from(json!("c1"))
                ),
                after: variablemap!(
                  "tags" => VariableValue::from(json!("tag2")),
                  "status" => VariableValue::from(json!("active")),
                  "id" => VariableValue::from(json!("c1"))
                ),
                row_signature: IGNORED_ROW_SIGNATURE,
            }
        ));
    }

    //Add contract 2
    {
        let change = SourceChange::Insert {
            element: Element::Node {
                metadata: ElementMetadata {
                    reference: ElementReference::new("test", "c2"),
                    labels: Arc::new([Arc::from("Contract")]),
                    effective_from: 0,
                },
                properties: ElementPropertyMap::from(json!({
                    "id": "c2",
                    "status": "cancelled",
                    "tags": "tag1"
                })),
            },
        };

        let result = opt_query
            .process_source_change(change.clone())
            .await
            .unwrap();
        assert_eq!(result.len(), 0);
    }

    //update contract 1 tags
    {
        let change = SourceChange::Update {
            element: Element::Node {
                metadata: ElementMetadata {
                    reference: ElementReference::new("test", "c1"),
                    labels: Arc::new([Arc::from("Contract")]),
                    effective_from: 0,
                },
                properties: ElementPropertyMap::from(json!({
                    "id": "c1",
                    "status": "active",
                    "tags": "tag3"
                })),
            },
        };

        let result = opt_query
            .process_source_change(change.clone())
            .await
            .unwrap();

        assert_eq!(result.len(), 1);

        assert!(contains_data(
            &result,
            &QueryPartEvaluationContext::Updating {
                before: variablemap!(
                  "tags" => VariableValue::from(json!("tag2")),
                  "status" => VariableValue::from(json!("active")),
                  "id" => VariableValue::from(json!("c1"))
                ),
                after: variablemap!(
                  "tags" => VariableValue::from(json!("tag3")),
                  "status" => VariableValue::from(json!("active")),
                  "id" => VariableValue::from(json!("c1"))
                ),
                row_signature: IGNORED_ROW_SIGNATURE,
            }
        ));
    }

    //update contract 2 with active status
    {
        let change = SourceChange::Update {
            element: Element::Node {
                metadata: ElementMetadata {
                    reference: ElementReference::new("test", "c2"),
                    labels: Arc::new([Arc::from("Contract")]),
                    effective_from: 0,
                },
                properties: ElementPropertyMap::from(json!({
                    "id": "c2",
                    "status": "active",
                    "tags": "tag1"
                })),
            },
        };

        let result = opt_query
            .process_source_change(change.clone())
            .await
            .unwrap();

        assert_eq!(result.len(), 0);
    }

    //update contract 2 with pending status
    {
        let change = SourceChange::Update {
            element: Element::Node {
                metadata: ElementMetadata {
                    reference: ElementReference::new("test", "c2"),
                    labels: Arc::new([Arc::from("Contract")]),
                    effective_from: 0,
                },
                properties: ElementPropertyMap::from(json!({
                    "id": "c2",
                    "status": "pending",
                    "tags": "tag1"
                })),
            },
        };

        let result = opt_query
            .process_source_change(change.clone())
            .await
            .unwrap();

        assert_eq!(result.len(), 0);
    }

    //update contract 2 with active status
    {
        let change = SourceChange::Update {
            element: Element::Node {
                metadata: ElementMetadata {
                    reference: ElementReference::new("test", "c2"),
                    labels: Arc::new([Arc::from("Contract")]),
                    effective_from: 0,
                },
                properties: ElementPropertyMap::from(json!({
                    "id": "c2",
                    "status": "active",
                    "tags": "tag1"
                })),
            },
        };

        let result = opt_query
            .process_source_change(change.clone())
            .await
            .unwrap();

        assert_eq!(result.len(), 1);
        assert!(contains_data(
            &result,
            &QueryPartEvaluationContext::Adding {
                after: variablemap!(
                  "tags" => VariableValue::from(json!("tag1")),
                  "status" => VariableValue::from(json!("active")),
                  "id" => VariableValue::from(json!("c2"))
                ),
                row_signature: IGNORED_ROW_SIGNATURE,
            }
        ));
    }
}

pub async fn prev_unique_with_match(config: &(impl QueryTestConfig + Send)) {
    let opt_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::prev_distinct_match_query(), parser)
            .with_function_registry(function_registry);
        builder = config.config_query(builder).await;
        builder.build().await
    };

    //Add contract 1
    {
        let change = SourceChange::Insert {
            element: Element::Node {
                metadata: ElementMetadata {
                    reference: ElementReference::new("test", "c1"),
                    labels: Arc::new([Arc::from("Contract")]),
                    effective_from: 0,
                },
                properties: ElementPropertyMap::from(json!({
                    "id": "c1",
                    "status": "pending",
                    "tags": "tag1"
                })),
            },
        };

        let result = opt_query
            .process_source_change(change.clone())
            .await
            .unwrap();
        assert_eq!(result.len(), 0);
    }

    //update contract 1 with active status
    {
        let change = SourceChange::Update {
            element: Element::Node {
                metadata: ElementMetadata {
                    reference: ElementReference::new("test", "c1"),
                    labels: Arc::new([Arc::from("Contract")]),
                    effective_from: 0,
                },
                properties: ElementPropertyMap::from(json!({
                    "id": "c1",
                    "status": "active",
                    "tags": "tag1"
                })),
            },
        };

        let result = opt_query
            .process_source_change(change.clone())
            .await
            .unwrap();

        assert_eq!(result.len(), 1);

        assert!(contains_data(
            &result,
            &QueryPartEvaluationContext::Adding {
                after: variablemap!(
                  "tags" => VariableValue::from(json!("tag1")),
                  "status" => VariableValue::from(json!("active")),
                  "id" => VariableValue::from(json!("c1"))
                ),
                row_signature: IGNORED_ROW_SIGNATURE,
            }
        ));
    }

    //update contract 1 tags
    {
        let change = SourceChange::Update {
            element: Element::Node {
                metadata: ElementMetadata {
                    reference: ElementReference::new("test", "c1"),
                    labels: Arc::new([Arc::from("Contract")]),
                    effective_from: 0,
                },
                properties: ElementPropertyMap::from(json!({
                    "id": "c1",
                    "status": "active",
                    "tags": "tag2"
                })),
            },
        };

        let result = opt_query
            .process_source_change(change.clone())
            .await
            .unwrap();

        assert_eq!(result.len(), 1);

        assert!(contains_data(
            &result,
            &QueryPartEvaluationContext::Updating {
                before: variablemap!(
                  "tags" => VariableValue::from(json!("tag1")),
                  "status" => VariableValue::from(json!("active")),
                  "id" => VariableValue::from(json!("c1"))
                ),
                after: variablemap!(
                  "tags" => VariableValue::from(json!("tag2")),
                  "status" => VariableValue::from(json!("active")),
                  "id" => VariableValue::from(json!("c1"))
                ),
                row_signature: IGNORED_ROW_SIGNATURE,
            }
        ));
    }

    //Add contract 2
    {
        let change = SourceChange::Insert {
            element: Element::Node {
                metadata: ElementMetadata {
                    reference: ElementReference::new("test", "c2"),
                    labels: Arc::new([Arc::from("Contract")]),
                    effective_from: 0,
                },
                properties: ElementPropertyMap::from(json!({
                    "id": "c2",
                    "status": "cancelled",
                    "tags": "tag1"
                })),
            },
        };

        let result = opt_query
            .process_source_change(change.clone())
            .await
            .unwrap();
        assert_eq!(result.len(), 0);
    }

    //update contract 1 tags
    {
        let change = SourceChange::Update {
            element: Element::Node {
                metadata: ElementMetadata {
                    reference: ElementReference::new("test", "c1"),
                    labels: Arc::new([Arc::from("Contract")]),
                    effective_from: 0,
                },
                properties: ElementPropertyMap::from(json!({
                    "id": "c1",
                    "status": "active",
                    "tags": "tag3"
                })),
            },
        };

        let result = opt_query
            .process_source_change(change.clone())
            .await
            .unwrap();

        assert_eq!(result.len(), 1);

        assert!(contains_data(
            &result,
            &QueryPartEvaluationContext::Updating {
                before: variablemap!(
                  "tags" => VariableValue::from(json!("tag2")),
                  "status" => VariableValue::from(json!("active")),
                  "id" => VariableValue::from(json!("c1"))
                ),
                after: variablemap!(
                  "tags" => VariableValue::from(json!("tag3")),
                  "status" => VariableValue::from(json!("active")),
                  "id" => VariableValue::from(json!("c1"))
                ),
                row_signature: IGNORED_ROW_SIGNATURE,
            }
        ));
    }

    //update contract 2 with active status
    {
        let change = SourceChange::Update {
            element: Element::Node {
                metadata: ElementMetadata {
                    reference: ElementReference::new("test", "c2"),
                    labels: Arc::new([Arc::from("Contract")]),
                    effective_from: 0,
                },
                properties: ElementPropertyMap::from(json!({
                    "id": "c2",
                    "status": "active",
                    "tags": "tag1"
                })),
            },
        };

        let result = opt_query
            .process_source_change(change.clone())
            .await
            .unwrap();

        assert_eq!(result.len(), 0);
    }

    //update contract 2 with pending status
    {
        let change = SourceChange::Update {
            element: Element::Node {
                metadata: ElementMetadata {
                    reference: ElementReference::new("test", "c2"),
                    labels: Arc::new([Arc::from("Contract")]),
                    effective_from: 0,
                },
                properties: ElementPropertyMap::from(json!({
                    "id": "c2",
                    "status": "pending",
                    "tags": "tag1"
                })),
            },
        };

        let result = opt_query
            .process_source_change(change.clone())
            .await
            .unwrap();

        assert_eq!(result.len(), 0);
    }

    //update contract 2 with active status
    {
        let change = SourceChange::Update {
            element: Element::Node {
                metadata: ElementMetadata {
                    reference: ElementReference::new("test", "c2"),
                    labels: Arc::new([Arc::from("Contract")]),
                    effective_from: 0,
                },
                properties: ElementPropertyMap::from(json!({
                    "id": "c2",
                    "status": "active",
                    "tags": "tag1"
                })),
            },
        };

        let result = opt_query
            .process_source_change(change.clone())
            .await
            .unwrap();

        assert_eq!(result.len(), 1);
        assert!(contains_data(
            &result,
            &QueryPartEvaluationContext::Adding {
                after: variablemap!(
                  "tags" => VariableValue::from(json!("tag1")),
                  "status" => VariableValue::from(json!("active")),
                  "id" => VariableValue::from(json!("c2"))
                ),
                row_signature: IGNORED_ROW_SIGNATURE,
            }
        ));
    }
}
