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
  }
}

# Terraform backends cannot contain interpolations
terraform {
  backend "s3" {
    bucket  = "orcd-terraform-state"
    key     = "qa/ows-royalties/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_caller_identity" "current" {}

module "lambda_function_info" {
  for_each            = toset(local.downstream_lambda_functions)
  source              = "git@github.com:theorchard/terraform-service-info.git//?ref=1.1.0"
  service_name        = each.value
  security_group_type = "lambda"
  environment         = var.environment
}

module "ows_royalties_owsrequest" {
  source             = "git@github.com:theorchard/terraform-owsrequest.git//?ref=1.1.0"
  policy_description = "A policy to access dynamo owsrequest table"
  environment_name   = var.environment
  service_name       = var.service_name
}

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

  providers = {
    aws.dns = aws.networking
  }

  environment                              = var.environment
  service_name                             = var.service_name
  aws_region                               = var.aws_region
  commit_sha                               = "latest"
  container_port                           = "8080"
  task_type                                = "web_service"
  desired_task_count                       = 6
  task_cpu                                 = 512
  task_memory                              = 1024
  maximum_capacity                         = 6
  minimum_capacity                         = 6
  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]
  fargate_service_subnets                  = module.vpc_info.default_private_subnet_ids
  load_balancer_subnets                    = module.vpc_info.default_private_subnet_ids
  application_family                       = var.application_family

  iam_managed_policy_attachments = concat(
    [module.ows_royalties_owsrequest.policy_arn_output],
    [for policy in data.aws_iam_policy.existing_policies_to_attach : policy.arn],
    [aws_iam_policy.abacus_airflow_cli_access_policy.arn],
    [module.s3_abacus_quarantine_bucket.s3_read_only_policy_arn_output],
    [aws_iam_policy.abacus_quarantine_bucket_write_access_policy.arn],
  )

  https_listener_allow_security_group_ids = flatten([
    [for lambda in module.lambda_function_info : lambda.security_groups],
  ])

  https_listener_allow_prefix_list_names = [
    "qa-accounting-private-subnet-prefix-list",
    "qa-orcd-private-subnet-prefix-list",
  ]

  environment_variables = [
    {
      Environment = var.environment
    },
    {
      LOGGER_DSN = "https://${var.environment}-fluentd-applications.theorchard.io:8888/application"
    },
    {
      MYSQL_DB_HOST = var.db_host
    },
    {
      MYSQL_DB_PORT = "3306"
    },
    {
      MYSQL_DB_NAME = var.db_name
    },
    {
      HISTORICAL_ISO_CODES = "BYR,EEK,LTL,LVL,MRO,SKK,STD,TMM,VEF,ZWD"
    },
    {
      S3_SALES_BUCKET_NAME = var.s3_sales_bucket
    },
    {
      MYSQL_DB_USER = var.db_user
    },
    {
      S3_ABACUS_ADJUSTMENTS_BUCKET = var.s3_abacus_adjustments_bucket
    },
    {
      S3_ABACUS_QUARANTINE_BUCKET = "${var.environment}-${var.s3_abacus_quarantine_bucket}"
    },
    {
      SPLITIO_USE_PREFORKED_INITIALIZATION = "false"
    },
    {
      KAFKA_BOOTSTRAP_SERVERS = var.kafka_bootstrap_servers
    },
    {
      SCHEMA_REGISTRY_URL = var.schema_registry_url
    },
    {
      SNOWFLAKE_ACCOUNT = var.snowflake_account
    },
    {
      SNOWFLAKE_ROLE = var.snowflake_role
    },
    {
      SNOWFLAKE_WAREHOUSE = var.snowflake_warehouse
    },
    {
      SNOWFLAKE_DATABASE = var.snowflake_database
    },
    {
      SNOWFLAKE_SCHEMA = var.snowflake_schema
    },
    {
      SNOWFLAKE_USER = var.snowflake_user
    },
    {
      SENTRY_DSN = module.sentry_ows_royalties.sentry_key_dsn_public_output
    },
    {
      RATELIMIT_STORAGE_URI = "rediss://${module.ows_royalties_ratelimit_cache.redis_primary_endpoint_address}:6379"
    },
  ]

  secrets = [
    {
      MYSQL_DB_PASS = "${var.environment}/${var.service_name}/MYSQL_DB_PASS"
    },
    {
      SNOWFLAKE_KEY_PASSPHRASE = "${var.environment}/${var.service_name}/SNOWFLAKE_KEY_PASSPHRASE"
    },
    {
      SNOWFLAKE_PRIVATE_KEY = "${var.environment}/${var.service_name}/SNOWFLAKE_PRIVATE_KEY"
    }
  ]
}

resource "aws_iam_policy" "abacus_airflow_cli_access_policy" {
  name        = "${var.environment}-${var.service_name}-abacus-airflow-cli-access-policy"
  description = "Policy to allow creating cli tokens to query dags"
  policy = jsonencode({
    Version = "2012-10-17"
    Statement = [
      {
        Effect   = "Allow"
        Action   = ["airflow:CreateCliToken"]
        Resource = [local.airflow_arn]
      }
    ]
  })
  tags = {
    environment        = var.environment
    service_name       = var.service_name
    application_family = var.application_family
  }
}

module "fargate_service_dashboard" {
  source             = "git@github.com:theorchard/terraform-datadog.git//modules/service?ref=6.18.1"
  environment        = var.environment
  environment_type   = "fargate"
  service_name       = var.service_name
  application_family = var.application_family

  notification_endpoints            = "@slack-monitoring"
  escalation_notification_endpoints = "@slack-monitoring"
}

module "sentry_ows_royalties" {
  source = "git@github.com:theorchard/terraform-sentry.git//?ref=5.0.0"

  environment        = var.environment
  platform           = "python"
  service_name       = var.service_name
  teams              = ["abacus-${var.environment}"]
  application_family = var.application_family
}

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

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

data "aws_iam_policy" "existing_policies_to_attach" {
  for_each = toset(var.existing_policies_to_attach)
  name     = each.value
}

module "s3_abacus_quarantine_bucket" {
  source              = "git@github.com:theorchard/terraform-s3.git//modules/s3_bucket?ref=3.15.7"
  bucket_name         = var.s3_abacus_quarantine_bucket
  application_family  = var.application_family
  kms_key_enabled     = false
  s3_read_only_policy = true

  env = var.environment

  apply_server_side_encryption_by_default = {
    sse_algorithm = "AES256"
  }
}

data "aws_iam_policy_document" "s3_abacus_quarantine_bucket_write_access_document" {
  statement {
    effect = "Allow"

    actions = [
      "s3:PutObject"
    ]

    resources = [
      "${module.s3_abacus_quarantine_bucket.s3_bucket_arn_output}/*"
    ]
  }
}

resource "aws_iam_policy" "abacus_quarantine_bucket_write_access_policy" {
  name        = "${var.environment}-abacus-quarantine-bucket-write-access-policy"
  description = "Policy for qa-abacus-quarantine bucket write permissions"
  policy      = data.aws_iam_policy_document.s3_abacus_quarantine_bucket_write_access_document.json
}
