/*
 * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
 * or more contributor license agreements. Licensed under the Elastic License
 * 2.0; you may not use this file except in compliance with the Elastic License
 * 2.0.
 */

import org.elasticsearch.gradle.testclusters.StandaloneRestIntegTestTask
import org.elasticsearch.gradle.util.GradleUtils

apply plugin: 'elasticsearch.internal-yaml-rest-test'
apply plugin: 'elasticsearch.yaml-rest-compat-test'
apply plugin: 'elasticsearch.validate-rest-spec'
apply plugin: 'elasticsearch.internal-test-artifact'

base {
  archivesName = 'x-pack'
}

dependencies {
  testImplementation project(xpackModule('core'))
  testImplementation(testArtifact(project(xpackModule('core'))))
  testImplementation(testArtifact(project(":x-pack:plugin:security:qa:service-account"), "javaRestTest"))
  testImplementation project(':test:yaml-rest-runner')
}

// let the yamlRestTests see the classpath of test
GradleUtils.extendSourceSet(project, "test", "yamlRestTest", tasks.named("yamlRestTest"))
GradleUtils.extendSourceSet(project, "test", "yamlRestCompatTest")

restResources {
  restApi {
    include '*'
  }
}

artifacts {
  restXpackTests(new File(projectDir, "src/yamlRestTest/resources/rest-api-spec/test"))
}

def restTestBlacklist = []
// TODO: fix this rest test to not depend on a hardcoded port!
restTestBlacklist.addAll(['getting_started/10_monitor_cluster_health/*'])
if (buildParams.snapshotBuild == false) {
  // these tests attempt to install basic/internal licenses signed against the dev/public.key
  // Since there is no infrastructure in place (anytime soon) to generate licenses using the production
  // private key, these tests are blacklisted in non-snapshot test runs
  restTestBlacklist.addAll(['xpack/15_basic/*', 'license/20_put_license/*', 'license/30_enterprise_license/*'])

  // TODO: Remove the following when the following features are released. These tests include new privileges only available under feature flags
  //  which require snapshot builds:
  // * Data Stream Lifecycle. manage_data_stream_lifecycle privilege is only available with dlm_feature_flag_enabled set
  // We disable these tests for snapshot builds to maintain release build coverage.
  restTestBlacklist.add('privileges/11_builtin/Test get builtin privileges')
}

tasks.withType(StandaloneRestIntegTestTask).configureEach {
  usesDefaultDistribution("to be triaged")
}

tasks.named("yamlRestTest").configure {
  systemProperty 'tests.rest.blacklist', restTestBlacklist.join(',')
}

tasks.register('enforceApiSpecsConvention').configure {
  def mainApiSpecs = fileTree('src/test/resources/rest-api-spec/api')
  doLast {
    if (mainApiSpecs.files) {
      throw new GradleException("There are REST specs in src/test source set. These should be moved to the :rest-api-spec project.")
    }
  }
}

tasks.register('enforceYamlTestConvention').configure {
  def mainYamlFiles = fileTree('src/test/resources/rest-api-spec/test')
  doLast {
    if (mainYamlFiles.files) {
      throw new GradleException("There are YAML tests in src/test source set. These should be moved to src/yamlRestTest.")
    }
  }
}

tasks.named("precommit").configure {
  dependsOn 'enforceYamlTestConvention', 'enforceApiSpecsConvention'
}

tasks.named("yamlRestCompatTestTransform").configure({ task ->
  task.skipTest("esql/60_usage/Basic ESQL usage output (telemetry)", "The telemetry output changed. We dropped a column. That's safe.")
  task.skipTest("inference/inference_crud/Test get all", "Assertions on number of inference models break due to default configs")
  task.skipTest("esql/60_usage/Basic ESQL usage output (telemetry) snapshot version", "The number of functions is constantly increasing")
  task.skipTest("esql/60_usage/Basic ESQL usage output (telemetry) non-snapshot version", "The number of functions is constantly increasing")
  task.skipTest("esql/80_text/reverse text", "The output type changed from TEXT to KEYWORD.")
  task.skipTest("esql/80_text/values function", "The output type changed from TEXT to KEYWORD.")
  task.skipTest("privileges/11_builtin/Test get builtin privileges" ,"unnecessary to test compatibility")
  task.skipTest("esql/61_enrich_ip/Invalid IP strings", "We switched from exceptions to null+warnings for ENRICH runtime errors")
  task.skipTest("esql/180_match_operator/match with non text field", "Match operator can now be used on non-text fields")
  task.skipTest("esql/180_match_operator/match with functions", "Error message changed")
  task.skipTest("esql/180_match_operator/match within eval", "Error message changed")
  task.skipTest("esql/40_unsupported_types/semantic_text declared in mapping", "The semantic text field format changed")
  task.skipTest("esql/190_lookup_join/Alias as lookup index", "LOOKUP JOIN does not support index aliases for now")
  task.skipTest("esql/190_lookup_join/alias-repeated-alias", "LOOKUP JOIN does not support index aliases for now")
  task.skipTest("esql/190_lookup_join/alias-repeated-index", "LOOKUP JOIN does not support index aliases for now")
  task.skipTest("esql/190_lookup_join/alias-pattern-multiple", "LOOKUP JOIN does not support index aliases for now")
  task.skipTest("esql/190_lookup_join/alias-pattern-single", "LOOKUP JOIN does not support index aliases for now")
  task.skipTest("esql/180_match_operator/match with disjunctions", "Disjunctions in full text functions work now")
  task.skipTest("esql/130_spatial/values unsupported for geo_point", "Spatial types are now supported in VALUES aggregation")
  task.skipTest("esql/130_spatial/values unsupported for geo_point status code", "Spatial types are now supported in VALUES aggregation")
  // Expected deprecation warning to compat yaml tests:
  task.addAllowedWarningRegex(
    ".*rollup functionality will be removed in Elasticsearch.*",
    // https://github.com/elastic/elasticsearch/issues/127911
    "Index \\[\\.profiling-.*\\] name begins with a dot.* and will not be allowed in a future Elasticsearch version."
  )
  task.skipTest("esql/40_tsdb/from doc with aggregate_metric_double", "TODO: support for subset of metric fields")
  task.skipTest("esql/40_tsdb/stats on aggregate_metric_double", "TODO: support for subset of metric fields")
  task.skipTest("esql/40_tsdb/from index pattern unsupported counter", "TODO: support for subset of metric fields")
  task.skipTest("esql/40_unsupported_types/unsupported", "TODO: support for subset of metric fields")
  task.skipTest("esql/40_unsupported_types/unsupported with sort", "TODO: support for subset of metric fields")
  task.skipTest("service_accounts/10_basic/Test get service accounts", "Enterprise Search service account removed, invalidating the current tests")
  task.skipTest("service_accounts/10_basic/Test service account tokens", "Enterprise Search service account removed, invalidating the current tests")
  task.skipTest("ml/3rd_party_deployment/Test clear deployment cache", "Deprecated route removed")
  task.skipTest("ml/3rd_party_deployment/Test start and stop deployment with cache", "Deprecated route removed")
  task.skipTest("ml/3rd_party_deployment/Test start and stop multiple deployments", "Deprecated route removed")
  task.skipTest("ml/3rd_party_deployment/Test update model alias on pytorch model to undeployed model", "Deprecated route removed")
  task.skipTest("ml/job_cat_apis/Test cat anomaly detector jobs", "Flush API is deprecated")
  task.skipTest("ml/jobs_get_stats/Test get job stats after uploading data prompting the creation of some stats", "Flush API is deprecated")
  task.skipTest("ml/jobs_get_stats/Test get job stats for closed job", "Flush API is deprecated")
  task.skipTest("ml/inference_crud/Test deprecation of include model definition param", "Query parameter removed")
  task.skipTest("ml/post_data/Test flush and close job WITHOUT sending any data", "Flush API is deprecated")
  task.skipTest("ml/post_data/Test flush with skip_time", "Flush API is deprecated")
  task.skipTest("ml/post_data/Test POST data job api, flush, close and verify DataCounts doc", "Flush API is deprecated")
  task.replaceValueInMatch("Size", 49, "Test flamegraph from profiling-events")
  task.replaceValueInMatch("Size", 49, "Test flamegraph from test-events")
  task.skipTest("esql/90_non_indexed/fetch", "Temporary until backported")
  task.skipTest("esql/63_enrich_int_range/Invalid age as double", "TODO: require disable allow_partial_results")
  task.skipTest("esql/191_lookup_join_on_datastreams/data streams not supported in LOOKUP JOIN", "Added support for aliases in JOINs")
  task.skipTest("esql/190_lookup_join/non-lookup index", "Error message changed")
  task.skipTest("esql/190_lookup_join/fails with non-lookup index", "Error message changed")
  task.skipTest("esql/192_lookup_join_on_aliases/alias-pattern-multiple", "Error message changed")
  task.skipTest("esql/192_lookup_join_on_aliases/fails when alias or pattern resolves to multiple", "Error message changed")
  task.skipTest("esql/10_basic/Test wrong LIMIT parameter", "Error message changed")
  task.skipTest("ml/sparse_vector_search/Search on a sparse_vector field with dots in the field names", "Vectors are no longer returned by default")
  task.skipTest("ml/sparse_vector_search/Search on a nested sparse_vector field with dots in the field names and conflicting child fields", "Vectors are no longer returned by default")
  task.skipTest("esql/190_lookup_join/lookup-no-key-only-key", "Requires the fix")
  task.skipTest("esql/40_tsdb/aggregate_metric_double unsortable", "Extra function required to enable the field type")
  task.skipTest("esql/40_tsdb/avg of aggregate_metric_double", "Extra function required to enable the field type")
  task.skipTest("esql/40_tsdb/grouping stats on aggregate_metric_double", "Extra function required to enable the field type")
  task.skipTest("esql/40_tsdb/render aggregate_metric_double when missing min and max", "Extra function required to enable the field type")
  task.skipTest("esql/40_tsdb/render aggregate_metric_double when missing value", "Extra function required to enable the field type")
  task.skipTest("esql/40_tsdb/sorting with aggregate_metric_double with partial submetrics", "Extra function required to enable the field type")
  task.skipTest("esql/40_tsdb/stats on aggregate_metric_double missing min and max", "Extra function required to enable the field type")
  task.skipTest("esql/40_tsdb/to_string aggregate_metric_double", "Extra function required to enable the field type")
  task.skipTest("esql/40_tsdb/stats on aggregate_metric_double with partial submetrics", "Extra function required to enable the field type")
  task.skipTest("esql/46_downsample/MV_EXPAND on non-MV aggregate metric double", "Extra function required to enable the field type")
  task.skipTest("esql/46_downsample/Query stats on downsampled index", "Extra function required to enable the field type")
  task.skipTest("esql/46_downsample/Render stats from downsampled index", "Extra function required to enable the field type")
  task.skipTest("esql/46_downsample/Sort from multiple indices one with aggregate metric double", "Extra function required to enable the field type")
})

tasks.named('yamlRestCompatTest').configure {
  systemProperty 'es.queryable_built_in_roles_enabled', 'false'
}
