################
# Platform Service — Secrets, Fargate, Datadog
################
# The platform service handles authorization, multi-tenancy, compliance,
# and entitlement management. It runs on Fargate behind an internal ALB
# exposing a ConnectRPC API on port 8082. It shares the existing Aurora
# MySQL (RDS) and ElastiCache Redis with the main app.
#
# All resources are gated by is_ephemeral — only deployed in the main environment.
# local.platform_service_name and local.platform_port are defined in main.tf.

################
# Secrets — Sentry + Audit encryption key
################

module "ows_coda_platform_secrets" {
  source = "git@github.com:theorchard/terraform-secrets-manager.git//?ref=1.6.1"
  for_each = local.is_ephemeral ? toset([]) : toset([
    "AUDIT_MASTER_KEY",
    "CODA_DB_PASS",
  ])

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

################
# Sentry — Platform service project
################

module "sentry_ows_coda_platform" {
  count  = local.is_ephemeral ? 0 : 1
  source = "git@github.com:theorchard/terraform-sentry.git//?ref=5.1.0"

  environment        = var.environment
  platform           = "node"
  service_name       = local.platform_service_name
  teams              = ["coda"]
  application_family = var.application_family
}

################
# Datadog — Platform service dashboard
################

module "ows_coda_platform_service_dashboard" {
  count                             = local.is_ephemeral ? 0 : 1
  source                            = "git@github.com:theorchard/terraform-datadog.git//modules/service?ref=6.19.0"
  environment                       = var.environment
  environment_type                  = "fargate"
  service_name                      = local.platform_service_name
  application_family                = var.application_family
  teams                             = ["coda"]
  notification_endpoints            = local.datadog_notification_endpoints
  escalation_notification_endpoints = local.datadog_escalation_notification_endpoints
}

################
# Fargate — ECS cluster, task definition, service, ALB, security groups, DNS
################

module "platform_fargate" {
  count  = local.is_ephemeral ? 0 : 1
  source = "git@github.com:theorchard/terraform-fargate.git//?ref=6.5.0"

  providers = {
    aws.dns = aws.networking
  }

  environment        = var.environment
  service_name       = local.platform_service_name
  aws_region         = var.region
  application_family = var.application_family
  commit_sha         = "latest"
  container_port     = tostring(local.platform_port)
  task_type          = "web_service"

  container_protocol_version = "HTTP1"
  health_check_matcher       = "200"

  # Platform service is lightweight (authorization checks + DB queries).
  # Start with minimal sizing — scale up based on observed load.
  desired_task_count = 2 # Minimum 2 for HA
  task_cpu           = 512
  task_memory        = 1024
  maximum_capacity   = 4
  minimum_capacity   = 2

  load_balancer_access_logs_s3_bucket_name = local.elb_logs_bucket
  blocking_waf_enabled                     = true

  vpc_id                           = module.vpc_info.vpc_id
  https_listener_certificate_id    = split("/", data.aws_acm_certificate.theorchard_io.arn)[1]
  health_check_path                = "/health"
  health_check_healthy_threshold   = 2
  health_check_unhealthy_threshold = 5

  secrets_manager_service_name = local.platform_service_name

  fargate_service_subnets = module.vpc_info.default_private_subnet_ids
  load_balancer_subnets   = module.vpc_info.default_public_subnet_ids

  secrets = [
    {
      AUDIT_MASTER_KEY = "${var.environment}/${local.platform_service_name}/AUDIT_MASTER_KEY"
    },
    {
      CODA_DB_PASS = "${var.environment}/${local.platform_service_name}/CODA_DB_PASS"
    },
  ]

  environment_variables = [
    {
      ENVIRONMENT = var.environment
    },
    {
      NODE_ENV = var.environment
    },
    {
      PORT = tostring(local.platform_port)
    },
    {
      # Shared Aurora MySQL — same DB as main app
      CODA_DB_HOST = local.rds_host
    },
    {
      CODA_DB_PORT = "3306"
    },
    {
      CODA_DB_USER = "coda_svc"
    },
    {
      CODA_DB_DATABASE = local.db_name
    },
    {
      # ElastiCache Redis — shared with main app
      REDIS_URL = "rediss://${local.redis_host}:6379"
    },
    {
      # Shadow mode — log permission checks but don't enforce (Phase 1 default)
      SHADOW_MODE = "true"
    },
    {
      SENTRY_DSN = try(module.sentry_ows_coda_platform[0].sentry_key_dsn_public_output, "")
    },
  ]
}
