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
}

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     = "prod/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" {}

locals {
  airflow_arn = "arn:aws:airflow:${var.aws_region}:${data.aws_caller_identity.current.account_id}:environment/prod-abacus-airflow"
}

# defined in prod/abacus-managed-airflow/iam.tf
data "aws_iam_policy" "royalties_sales_files_bucket_read_write_policy" {
  arn = "arn:aws:iam::${data.aws_caller_identity.current.account_id}:policy/S3-${var.environment}-sales-buckets-read-write-policy"
}

data "aws_iam_policy" "abacus_adjustments_usage_policy" {
  name = "S3-prod-abacus-adjustments-usage-policy"
}

module "ows_royalties_owsrequest" {
  source = "git@github.com:theorchard/terraform-owsrequest.git//?ref=1.1.0"

  environment_name = var.environment
  service_name     = var.service_name
}

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

  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           = 2048
  task_memory        = 4096
  maximum_capacity   = 8
  minimum_capacity   = 4
  route53_zone_id    = data.aws_route53_zone.route53_zone.zone_id

  vpc_id                        = module.vpc_info.vpc_id
  https_listener_certificate_id = split("/", data.aws_acm_certificate.theorchard_io.arn)[1]
  blocking_waf_enabled          = true
  application_family            = var.application_family

  iam_managed_policy_attachments = [
    module.ows_royalties_owsrequest.policy_arn_output,
    "arn:aws:iam::437795906767:policy/Elasticsearch-prod-ows-royalties-log-RW",
    "arn:aws:iam::437795906767:policy/SecretsManager-prod-ows-royalties-policy",
    data.aws_iam_policy.royalties_sales_files_bucket_read_write_policy.arn,
    data.aws_iam_policy.abacus_adjustments_usage_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,
  ]

  fargate_service_subnets = concat(["subnet-043d235081c966332", "subnet-067a6b45b079d7296"], module.vpc_info.default_private_subnet_ids)

  load_balancer_subnets = concat(["subnet-043d235081c966332", "subnet-067a6b45b079d7296"], module.vpc_info.default_private_subnet_ids)

  https_listener_allow_prefix_list_names = [
    "shared-orcd-jump-box-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
    },
    {
      MYSQL_DB_USER = var.db_user
    },
    {
      S3_SALES_BUCKET_NAME = var.s3_sales_bucket
    },
    {
      HISTORICAL_ISO_CODES = "BYR,EEK,LTL,LVL,MRO,SKK,STD,TMM,VEF,ZWD"
    },
    {
      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
    },
    {
      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"
    },
    {
      SENTRY_DSN = "${var.environment}/${var.service_name}/SENTRY_DSN"
    },
    {
      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 "ows_royalties_fargate_service_dashboard" {
  source = "git@github.com:theorchard/terraform-datadog.git//modules/service?ref=6.18.2"

  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
  dependent_applications            = var.dependent_applications
  teams                             = var.teams

  additional_tags = {
    provisioned_by = "terraform"
  }

  # Warn for at least 5 events and alert for more than 30 event over a 5m window
  service_5xx_monitor_enabled  = true
  warning_number_5xx           = 5
  warning_recovery_number_5xx  = 0
  critical_number_5xx          = 30
  critical_recovery_number_5xx = 0.1
  ok_number_5xx                = 0

  # 14-day baseline (2026-07): normal 5m 4xx counts average ~70-140 and peak
  # ~330, so the prior 10/20 warning/critical thresholds sat inside ordinary
  # traffic and flapped constantly. Set clear of the observed baseline with
  # headroom above the ~332 peak so legitimate peaks don't page: warning near
  # the top of normal, critical well above the observed max.
  service_4xx_monitor_enabled  = true
  warning_number_4xx           = 300
  warning_recovery_number_4xx  = 150
  critical_number_4xx          = 450
  critical_recovery_number_4xx = 250
  ok_number_4xx                = 0

  # PagerDuty notifications for 5xx events
  notification_overrides_5xx = {
    endpoints            = "${var.notification_endpoints}"
    alert_endpoints      = "${var.notification_endpoints} ${var.pagerduty_alert_channel}"
    escalation_endpoints = "${var.notification_endpoints} ${var.pagerduty_alert_channel}"
  }
}

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

  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
}

module "s3_abacus_quarantine_bucket" {
  source              = "git@github.com:theorchard/terraform-s3.git//modules/s3_bucket?ref=3.15.0"
  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 prod-abacus-quarantine bucket write permissions"
  policy      = data.aws_iam_policy_document.s3_abacus_quarantine_bucket_write_access_document.json
}
