data "cloudflare_ip_ranges" "cloudflare" {}

data "cloudflare_zone" "cloudflare_zone" {
  name = var.api_gateway_public_domain
}

data "aws_nat_gateways" "nat_gateways" {
  vpc_id = module.vpc_info.vpc_id

  filter {
    name   = "state"
    values = ["available"]
  }
}

data "aws_nat_gateway" "nat_gateway" {
  count = length(data.aws_nat_gateways.nat_gateways.ids)
  id    = tolist(data.aws_nat_gateways.nat_gateways.ids)[count.index]
}

module "stripo_plugin_api_gateway" {
  source = "git@github.com:theorchard/terraform-fargate.git//?ref=6.1.1"

  providers = {
    aws.dns = aws
  }

  environment                              = var.environment
  service_name                             = "${var.service_name}-api-gateway"
  aws_region                               = var.aws_region
  application_family                       = var.application_family
  service_platform_version                 = "1.4.0"
  deployment_minimum_healthy_percent       = "100"
  desired_task_count                       = 1
  minimum_capacity                         = 1
  maximum_capacity                         = 1
  task_cpu                                 = 512
  task_memory                              = 1024
  container_port                           = 8080
  health_check_grace_period_seconds        = 300
  health_check_path                        = "/actuator/health/liveness"
  override_route53_zone_id                 = data.aws_route53_zone.route53_zone.id
  load_balancer_access_logs_s3_bucket_name = var.load_balancer_logs_bucket
  vpc_id                                   = module.vpc_info.vpc_id
  fargate_service_subnets                  = module.vpc_info.default_private_subnet_ids
  load_balancer_subnets                    = module.vpc_info.default_public_subnet_ids
  load_balancer_is_internal                = false
  non_ecr_image                            = "086679231553.dkr.ecr.us-east-1.amazonaws.com/stripo/stripo-plugin-api-gateway:1.175.0"
  custom_waf_arn                           = module.stripo_waf.waf_count_only_arn_output
  https_listener_certificate_id            = var.https_listener_certificate_id
  https_listener_allow_prefix_list_names = [
    "prod-orcd-private-subnet-prefix-list",
  ]
  prod_https_listener_allow_cidr_blocks = concat(
    [
      "192.168.31.0/24",
      "10.40.0.0/22",
      "10.10.40.0/22",
    ],
    [
      for ngw in data.aws_nat_gateway.nat_gateway : "${ngw.public_ip}/32"
    ]
  )

  environment_variables = [
    {
      Environment = var.environment
    },
    {
      DD_TRACE_ANALYTICS_ENABLED = "true"
    },
    {
      DD_TRACE_APP_NAME = "${var.environment}-${var.service_name}"
    },
    {
      APPNAME = "api-gateway"
    },
    {
      ENV = "PLUGINS"
    },
    {
      PROFILE = "PLUGINS"
    },
    {
      SPRING_CONFIG_NAME = "application,jdbc,log,base"
    },
    {
      SPRING_CLOUD_CONFIG_ENABLED = "false"
    },
    {
      JVM_MEMORY_OPTS = "-Dspring.cloud.config.enabled=false -Daws.secretsmanager.enabled=false"
    },
    {
      JAVA_TOOL_OPTIONS = "-Xss256k -Xms256m -Xmx400m -XX:ReservedCodeCacheSize=128M"
    },
    {
      LOGGING_LEVEL_ROOT = "INFO"
    },
    {
      SPRING_ZIPKIN_ENABLED = "false"
    },
    {
      JWT_SECRET_EXPIRATIONINMINUTES = "30"
    },
    {
      RATE_LIMIT_PUBLICRULES = "[{'limit':10000,'durationSecond':60},{'limit':100000,'durationSecond':3600}]"
    },
    {
      RATE_LIMIT_ENABLED = "false"
    },
    {
      REDISSON_URL = "${module.redis_elasticache.redis_cluster_cname_output[0]}:6379"
    },
    {
      REDISSON_AUTHORIZED = "false"
    },
    {
      AUTH_INNERSERVICEUSERNAME = "innerPluginApiUsername"
    },
    {
      SERVICE_TIMER_USERNAME = "timeradmin"
    },
    {
      SERVICE_TIMER_URL = "https://${var.environment != "prod" ?
        module.stripo_time_api.non_prod_fargate_service_route53_record_fqdn_output :
      module.stripo_time_api.fargate_service_route53_record_fqdn_output}:443"
    },
    {
      SERVICE_AI_URL = "https://${var.environment != "prod" ?
        module.stripo_ai_service.non_prod_fargate_service_route53_record_fqdn_output :
      module.stripo_ai_service.fargate_service_route53_record_fqdn_output}:443"
    },
    {
      SERVICE_PLUGINDETAILS_URL = "https://${var.environment != "prod" ?
        module.stripo_plugin_details_service.non_prod_fargate_service_route53_record_fqdn_output :
      module.stripo_plugin_details_service.fargate_service_route53_record_fqdn_output}:443"
    },
    {
      SERVICE_CUSTOMBLOCKS_URL = "https://${var.environment != "prod" ?
        module.stripo_plugin_custom_blocks_service.non_prod_fargate_service_route53_record_fqdn_output :
      module.stripo_plugin_custom_blocks_service.fargate_service_route53_record_fqdn_output}:443"
    },
    {
      SERVICE_DRAFTS_URL = "https://${var.environment != "prod" ?
        module.stripo_plugin_drafts_service.non_prod_fargate_service_route53_record_fqdn_output :
      module.stripo_plugin_drafts_service.fargate_service_route53_record_fqdn_output}:443"
    },
    {
      SERVICE_DOCUMENTS_URL = "https://${var.environment != "prod" ?
        module.stripo_plugin_documents_service.non_prod_fargate_service_route53_record_fqdn_output :
      module.stripo_plugin_documents_service.fargate_service_route53_record_fqdn_output}:443"
    },
    {
      SERVICE_IMAGESBANK_URL = "https://${var.environment != "prod" ?
        module.stripo_plugin_image_bank_service.non_prod_fargate_service_route53_record_fqdn_output :
      module.stripo_plugin_image_bank_service.fargate_service_route53_record_fqdn_output}:443"
    },
    {
      SERVICE_HTMLGEN_URL = "https://${var.environment != "prod" ?
        module.stripo_html_gen_service.non_prod_fargate_service_route53_record_fqdn_output :
      module.stripo_html_gen_service.fargate_service_route53_record_fqdn_output}:443"
    },
    {
      SERVICE_HTMLCLEANER_URL = "https://${var.environment != "prod" ?
        module.stripo_html_cleaner_service.non_prod_fargate_service_route53_record_fqdn_output :
      module.stripo_html_cleaner_service.fargate_service_route53_record_fqdn_output}:443"
    },
    {
      SERVICE_STATISTICS_URL = "https://${var.environment != "prod" ?
        module.stripo_plugin_statistics_service.non_prod_fargate_service_route53_record_fqdn_output :
      module.stripo_plugin_statistics_service.fargate_service_route53_record_fqdn_output}:443"
    },
    {
      MANAGEMENT_TRACING_SAMPLING_PROBABILITY = "0"
    },
    {
      MANAGEMENT_SERVER_PORT = "8080"
    },
    {
      MANAGEMENT_ENDPOINTS_WEB_EXPOSURE_INCLUDE = "health,prometheus,metrics"
    },
    {
      MANAGEMENT_ENDPOINT_HEALTH_PROBES_ENABLED = "true"
    },
    {
      MANAGEMENT_ADDRESS = "0.0.0.0"
    },
    {
      MANAGEMENT_SECURITY_ENABLED = "false"
    }
  ]
  secrets = [
    {
      JWT_SECRET_CABINETKEY = "${var.environment}/${var.service_name}-api-gateway/JWT_SECRET_API_KEY"
    },
    {
      JWT_SECRET_CABINETKEYV2 = "${var.environment}/${var.service_name}-api-gateway/JWT_SECRET_API_KEY"
    },
    {
      JWT_SECRET_APIKEY = "${var.environment}/${var.service_name}-api-gateway/JWT_SECRET_API_KEY"
    },
    {
      JWT_SECRET_APIKEYV2 = "${var.environment}/${var.service_name}-api-gateway/JWT_SECRET_API_KEY"
    },
    {
      JWT_SECRET_APIKEYV3 = "${var.environment}/${var.service_name}-api-gateway/JWT_SECRET_API_KEY"
    },
    {
      AUTH_INNERSERVICEPASSWORD = "${var.environment}/${var.service_name}-api-gateway/APIGW_SERVICE_PASSWORD"
    },
    {
      SERVICE_TIME_PASSWORD = "${var.environment}/${var.service_name}-api-gateway/APIGW_SERVICE_PASSWORD"
    }
  ]
}

module "api_gateway_service_dashboard" {
  source                            = "git@github.com:theorchard/terraform-datadog.git//modules/service?ref=6.10.7"
  environment                       = var.environment
  environment_type                  = "fargate"
  service_name                      = "${var.service_name}-api-gateway"
  application_family                = var.application_family
  notification_endpoints            = var.application_alert_channel
  escalation_notification_endpoints = var.application_alert_channel
  teams                             = ["fansifter"]
}

resource "aws_security_group_rule" "stripo_api_gateway_ingress_from_cloudflare_rule" {
  type              = "ingress"
  protocol          = "tcp"
  cidr_blocks       = data.cloudflare_ip_ranges.cloudflare.ipv4_cidr_blocks
  from_port         = 443
  to_port           = 443
  security_group_id = module.stripo_plugin_api_gateway.fargate_load_balancer_security_group_id
}

resource "cloudflare_record" "stripo_api_gateway_public_cname" {
  zone_id = data.cloudflare_zone.cloudflare_zone.id
  name    = "${var.environment}-${var.service_name}-api-gateway"
  value   = module.stripo_plugin_api_gateway.fargate_service_route53_record_fqdn_output
  type    = "CNAME"
  proxied = true
}
