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.aws_region

  default_tags {
    tags = module.default_tags.tags
  }
}

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

  default_tags {
    tags = module.default_tags.tags
  }
}

data "aws_caller_identity" "current" {}

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

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

  environment = var.environment
}

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

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

data "aws_iam_policy_document" "sqs_message_policy" {
  statement {
    actions = [
      "sqs:SendMessageBatch",
      "sqs:SendMessage",
      "sqs:GetQueueUrl",
      "sqs:GetQueueAttributes"
    ]

    resources = [
      "arn:aws:sqs:*:${data.aws_caller_identity.current.account_id}:${var.environment}-fanout-event-queue",
    ]
  }
}

resource "aws_iam_policy" "sqs_message_policy" {
  name   = "SQS-${var.environment}-${var.service_name}-fanout-event-RW"
  policy = data.aws_iam_policy_document.sqs_message_policy.json
  tags = {
    application_family = var.application_family
    environment        = var.environment
    service_name       = var.service_name
    terraformed        = true
  }
}

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

  providers = {
    aws.dns = aws.networking
  }

  environment                              = var.environment
  service_name                             = var.service_name
  application_family                       = var.application_family
  aws_region                               = var.aws_region
  commit_sha                               = "latest"
  container_port                           = "8080"
  task_type                                = "web_service"
  desired_task_count                       = 2
  task_cpu                                 = 512
  task_memory                              = 1024
  maximum_capacity                         = 4
  minimum_capacity                         = 2
  health_check_path                        = "/hello/"
  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
  https_listener_certificate_id            = split("/", data.aws_acm_certificate.theorchard_io.arn)[1]
  iam_policy_file_enabled                  = true

  iam_managed_policy_attachments = [
    "arn:aws:iam::${data.aws_caller_identity.current.account_id}:policy/Dynamo-qa-ows-notifications-owsrequest",
    "arn:aws:iam::${data.aws_caller_identity.current.account_id}:policy/SQS-qa-notifications-RW",
    aws_iam_policy.sqs_message_policy.arn
  ]

  fargate_service_subnets = module.vpc_info.default_private_subnet_ids

  load_balancer_subnets = module.vpc_info.default_private_subnet_ids

  environment_variables = [
    {
      DATADOG_ENV = "${var.environment}-${var.service_name}"
    },
    {
      DD_LOGS_INJECTION = "true"
    },
    {
      DD_APM_ANALYZED_SPANS = "flask|flask.request=1,requests|requests.request=1"
    },
    {
      DD_TRACE_HEADER_TAGS = join(",", var.dd_trace_headers)
    },
    {
      Environment = var.environment
    },
    {
      AWS_ACCOUNT_ID = data.aws_caller_identity.current.account_id
    },
    {
      CONTENT_REVIEW_EMAIL_OVERRIDE = var.content_review_email_override
    },
    {
      SES_SENDER = "qa-notifications@theorchard.com"
    },
    {
      BULK_APP_SLACK_CHANNEL_ID = var.bulk_slack_channel_id
    },
    {
      REDIS_HOST = module.elasticache.redis_primary_endpoint_address
    },
    {
      REDIS_PORT = "6379"
    }
  ]
}

module "secrets" {
  source   = "git@github.com:theorchard/terraform-secrets-manager.git//?ref=1.5.1"
  for_each = toset(var.secrets_manager_secret_names)

  environment                    = var.environment
  service_name                   = var.service_name
  secret_name                    = each.value
  application_family             = var.application_family
  secret_recovery_window_in_days = 7
}

module "ows_notifications_dashboard" {
  source                            = "git@github.com:theorchard/terraform-datadog.git//modules/service?ref=6.15.3"
  environment                       = var.environment
  environment_type                  = "fargate"
  service_name                      = var.service_name
  application_family                = var.application_family
  notification_endpoints            = var.notification_endpoints
  escalation_notification_endpoints = var.notification_endpoints
}

# Create ses iam policy document.
data "aws_iam_policy_document" "ses_notifications_policy_document" {
  statement {
    effect = "Allow"
    resources = [
      "arn:aws:ses:us-east-1:${data.aws_caller_identity.current.account_id}:identity/qa-notifications@theorchard.com",
      "arn:aws:ses:us-east-1:${data.aws_caller_identity.current.account_id}:identity/theorchard.com",
      "arn:aws:ses:us-east-1:437795906767:configuration-set/prod-ses-email-events",
    ]

    actions = [
      "ses:SendEmail",
      "ses:SendRawEmail",
    ]
  }
}

# Create ses iam policy
resource "aws_iam_policy" "ses_notifications_policy" {
  name   = "SES-${var.environment}-${var.service_name}-policy"
  policy = data.aws_iam_policy_document.ses_notifications_policy_document.json
  tags = {
    application_family = var.application_family
    environment        = var.environment
    service_name       = var.service_name
    terraformed        = true
  }
}

# Attach ses iam policy to the task role
resource "aws_iam_role_policy_attachment" "ses_notifications_policy_attachment" {
  role       = module.ows_notifications_fargate_environment.fargate_task_iam_role_name
  policy_arn = aws_iam_policy.ses_notifications_policy.arn
}
