module "default_tags" {
  source             = "git@github.com:theorchard/terraform-default-tags.git//?ref=2.0.0"
  environment        = var.environment
  application_family = var.application_family
  service_name       = var.service_name
  team_name          = var.team_name
}

provider "aws" {
  region = var.region

  default_tags {
    tags = module.default_tags.tags
  }
}

provider "aws" {
  region  = var.region
  alias   = "networking"
  profile = "networking"

  default_tags {
    tags = module.default_tags.tags
  }
}

# Terraform backends cannot contain interpolations
terraform {
  backend "s3" {
    bucket  = "orcd-terraform-state"
    key     = "qa/ows-features/terraform.tfstate"
    region  = "us-east-1"
    encrypt = "true"
  }
}

module "vpc_info" {
  source = "git@github.com:theorchard/terraform-vpc-info.git?ref=3.0.2"

  environment = var.environment
}

data "aws_acm_certificate" "theorchard_io" {
  domain   = "*.theorchard.io"
  statuses = ["ISSUED"]
}

data "aws_route53_zone" "route53_zone" {
  name = "theorchard.io."
}

module "owsrequest" {
  source           = "git@github.com:theorchard/terraform-owsrequest.git//?ref=1.0.1"
  environment_name = var.environment
  service_name     = var.service_name
}

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

  providers = {
    aws.dns = aws.networking
  }

  application_family                       = var.application_family
  environment                              = var.environment
  service_name                             = var.service_name
  aws_region                               = var.region
  commit_sha                               = "latest"
  container_port                           = "8080"
  task_type                                = "web_service"
  desired_task_count                       = 12
  task_cpu                                 = 2048
  task_memory                              = 4096
  maximum_capacity                         = 16
  minimum_capacity                         = 8
  route53_zone_id                          = data.aws_route53_zone.route53_zone.zone_id
  load_balancer_access_logs_s3_bucket_name = "orch-elb-logs"
  vpc_id                                   = module.vpc_info.vpc_id
  fargate_service_subnets                  = module.vpc_info.default_private_subnet_ids
  load_balancer_subnets                    = module.vpc_info.default_private_subnet_ids
  https_listener_certificate_id            = split("/", data.aws_acm_certificate.theorchard_io.arn)[1]
  target_deregistration_delay              = 5
  health_check_grace_period_seconds        = 300
  container_start_period_seconds           = 300

  iam_managed_policy_attachments = [
    module.owsrequest.policy_arn_output
  ]

  environment_variables = [
    {
      Environment = var.environment
    },
    {
      LOGGER_DSN = "https://${var.environment}-fluentd-applications.theorchard.io:8888/application"
    },
    {
      LOGGER_LEVEL = var.LOGGER_LEVEL
    },
    {
      REDIS_CACHE_TTL = var.REDIS_CACHE_TTL
    },
    {
      SPLITIO_ENABLED = var.SPLITIO_ENABLED
    },
  ]
}

module "elasticache" {
  # checkov:skip=CKV_AWS_30:PP-1089 Upgrade code to use rediss
  # checkov:skip=CKV_AWS_31:PP-1089 Upgrade code to use rediss
  source = "git@github.com:theorchard/terraform-elasticache.git//?ref=3.1.1"

  providers = {
    aws.dns = aws.networking
  }

  environment                      = "qa"
  application_family               = var.application_family
  service_name                     = "ows-features"
  redis_engine_version             = "5.0.6"
  cache_engine                     = "redis"
  cache_subnet_group_name          = "prod-vpc-orchard-subnet"
  cache_node_count                 = "1"
  cache_node_type                  = "cache.t4g.micro"
  cache_parameter_group_name       = "default.redis5.0"
  cache_transit_encryption_enabled = false
  vpc_id                           = module.vpc_info.vpc_id
  route53_zone_id                  = data.aws_route53_zone.route53_zone.zone_id
}

module "fargate_service_dashboard" {
  source                            = "git@github.com:theorchard/terraform-datadog.git//modules/service?ref=6.10.7"
  application_family                = var.application_family
  environment                       = var.environment
  environment_type                  = "fargate"
  service_name                      = var.service_name
  notification_endpoints            = "@slack-permissions-platform-alerts"
  escalation_notification_endpoints = "@slack-permissions-platform-alerts"
  service_cpu_monitor_silenced      = true
  service_cpu_time_window           = "last_15m"
}

# Create IAM user for integration tests
resource "aws_iam_user" "integration_tests_iam_user" {
  name = "${var.environment}-${var.service_name}-integration-tests"
  tags = {
    environment  = var.environment
    service_name = var.service_name
    terraformed  = true
    role         = "service-user"
  }
}

data "aws_ecr_repository" "ecr_integration_test_repositories" {
  for_each = toset([var.service_name, "ows-users"])
  name     = each.value
}

data "aws_iam_policy_document" "ecr_integration_tests_policy_document" {
  statement {
    actions = [
      "ecr:BatchCheckLayerAvailability",
      "ecr:BatchGetImage",
      "ecr:DescribeImages",
      "ecr:DescribeImageScanFindings",
      "ecr:DescribeRepositories",
      "ecr:GetDownloadUrlForLayer",
      "ecr:GetLifecyclePolicy",
      "ecr:GetLifecyclePolicyPreview",
      "ecr:GetRepositoryPolicy",
      "ecr:ListImages",
      "ecr:ListTagsForResource",
      "ecr:TagResource",
      "ecr:UntagResource",
    ]

    resources = [for repository in data.aws_ecr_repository.ecr_integration_test_repositories : repository.arn]
  }

  statement {
    actions = [
      "ecr:GetAuthorizationToken"
    ]

    resources = [
      "*"
    ]
  }
}

resource "aws_iam_policy" "ecr_integration_tests_policy" {
  name   = "ECR-${var.service_name}-RO"
  policy = data.aws_iam_policy_document.ecr_integration_tests_policy_document.json
}

resource "aws_iam_user_policy_attachment" "ecr_integration_tests_policy_document_attachment" {
  user       = aws_iam_user.integration_tests_iam_user.name
  policy_arn = aws_iam_policy.ecr_integration_tests_policy.arn
}
