################
# Providers
################

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 {
  backend "s3" {
    bucket  = "orcd-terraform-state"
    key     = "prod/ows-coda/terraform.tfstate"
    region  = "us-east-1"
    encrypt = "true"
  }
}

################
# Data sources
################

data "aws_caller_identity" "current" {}

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

################
# Locals
################

locals {
  # Search service name — used across search.tf and ecs_ec2.tf (PR 2)
  search_service_name = "ows-coda-search"

  # Shared constants — extracted to avoid duplication across files
  graphql_gateway_url                       = "https://${var.environment}-graphql-router.theorchard.io/graphql"
  elb_logs_bucket                           = "orch-elb-logs"
  datadog_notification_endpoints            = "@slack-monitoring @slack-coda-monitoring"
  datadog_escalation_notification_endpoints = "@slack-coda-monitoring"

  rds_host  = module.ows_coda_rds.rds_cluster_endpoint
  s3_bucket = module.s3_ows_coda_uploads.s3_bucket_name_output
  s3_arn    = module.s3_ows_coda_uploads.s3_bucket_arn_output
  db_name   = "coda"
}

################
# Fargate
################

module "ows_coda_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.region

  application_family = var.application_family
  commit_sha         = "latest"
  container_port     = "8080"
  task_type          = "web_service"
  # Secrets populated, Prisma migration run — service is ready to serve traffic.
  desired_task_count                       = 2
  task_cpu                                 = 1024
  task_memory                              = 2048
  maximum_capacity                         = 8
  minimum_capacity                         = 2
  load_balancer_idle_timeout               = 300
  load_balancer_access_logs_s3_bucket_name = local.elb_logs_bucket
  vpc_id                                   = module.vpc_info.vpc_id
  https_listener_certificate_id            = split("/", data.aws_acm_certificate.theorchard_io.arn)[1]
  http_listener_enabled                    = false
  blocking_waf_enabled                     = true
  health_check_path                        = "/health"

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

  secrets = [
    {
      CODA_DB_PASS = "${var.environment}/${var.service_name}/CODA_DB_PASS"
    },
    {
      CODA_DB_IDENTITY_HMAC_SECRET = "${var.environment}/${var.service_name}/CODA_DB_IDENTITY_HMAC_SECRET"
    },
    {
      CODA_DB_IDENTITY_AES_KEY = "${var.environment}/${var.service_name}/CODA_DB_IDENTITY_AES_KEY"
    },
  ]

  environment_variables = [
    {
      AUTH0_AUDIENCE = var.auth0_audience
    },
    {
      AUTH0_CLIENT_ID = var.auth0_client_id
    },
    {
      AUTH0_DOMAIN = var.auth0_domain
    },
    {
      BEDROCK_REGION = var.region
    },
    {
      CODA_DB_DATABASE = local.db_name
    },
    {
      CODA_DB_HOST = local.rds_host
    },
    {
      CODA_DB_PORT = "3306"
    },
    {
      CODA_DB_USER = "coda_svc"
    },
    {
      DD_LOGS_INJECTION = true
    },
    {
      ENVIRONMENT = var.environment
    },
    {
      GRAPHQL_GATEWAY_URL = local.graphql_gateway_url
    },
    {
      NODE_ENV = var.environment
    },
    {
      OWS_ABACUS_ACCOUNT_URL = "https://prod-ows-abacus-account.theorchard.io/"
    },
    {
      OWS_ANALYTICS_URL = "https://prod-ows-analytics.theorchard.io/"
    },
    {
      OWS_MONEYHUB_URL = "https://prod-ows-moneyhub.theorchard.io/"
    },
    {
      OWS_PRODUCT_URL = "https://prod-ows-product.theorchard.io/"
    },
    {
      OWS_ROYALTIES_URL = "https://prod-ows-royalties.theorchard.io/"
    },
    {
      OWS_LEDGER_URL = "https://prod-ows-ledger.theorchard.io/"
    },
    {
      # rediss:// (double s) enables TLS. Requires cache_transit_encryption_enabled on the cluster.
      # Specify :6379 to ensure correct port. Some clients default to it, but explicit is safer.
      REDIS_URL = "rediss://${module.ows_coda_chatbot_cache.redis_primary_endpoint_address}:6379"
    },
    {
      S3_UPLOADS_BUCKET = local.s3_bucket
    },
    {
      S3_UPLOADS_REGION = var.region
    },
    {
      SENTRY_DSN = module.sentry_ows_coda.sentry_key_dsn_public_output
    },
    {
      FRONTEND_MONEYHUB_URL = "https://moneyhub.theorchard.com"
    },
    {
      FRONTEND_CONTENT_URL = "https://content.theorchard.com"
    },
    {
      FRONTEND_ROYALTIES_URL = "https://abacus.theorchard.com"
    },
    {
      # Search ALB will be created in PR 2 (COD-89_prod-search).
      SEARCH_URL = "https://${var.environment}-${local.search_service_name}.theorchard.io"
    },
  ]
}

################
# Secrets
################

# Secrets — injected into the Fargate container via the `secrets` parameter above
# SENTRY_AUTH_TOKEN: Sentry Vite plugin (sourcemaps). Also pulled by Jenkins via withCredentials.
# CODA_DB_PASS: Aurora service user (coda_svc). Used by the app for read/write.
# CODA_IDENTITY_*: HMAC and AES keys for identity hashing/encryption in the Coda DB.
module "ows_coda_secrets" {
  source = "git@github.com:theorchard/terraform-secrets-manager.git//?ref=1.5.1"
  for_each = toset([
    "CODA_DB_PASS",
    "CODA_DB_IDENTITY_AES_KEY",
    "CODA_DB_IDENTITY_HMAC_SECRET",
    "SENTRY_AUTH_TOKEN",
  ])

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

# SENTRY_DSN — created directly to auto-sync value from the Sentry project.
# Used at build time (baked into the client bundle) and at runtime (Fargate env var).
resource "aws_secretsmanager_secret" "sentry_dsn" {
  name        = "${var.environment}/${var.service_name}/SENTRY_DSN"
  description = "Sentry DSN for ows-coda (auto-synced from Sentry module)"

  tags = {
    environment        = var.environment
    application_family = var.application_family
    service_name       = var.service_name
  }
}

# Keeps the secret value in sync with the Sentry project DSN.
resource "aws_secretsmanager_secret_version" "sentry_dsn" {
  secret_id     = aws_secretsmanager_secret.sentry_dsn.id
  secret_string = module.sentry_ows_coda.sentry_key_dsn_public_output
}

################
# Sentry
################

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

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

################
# Datadog
################

module "ows_coda_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
  teams                             = ["coda"]
  notification_endpoints            = local.datadog_notification_endpoints
  escalation_notification_endpoints = local.datadog_escalation_notification_endpoints
}

################
# Bedrock IAM
################

# Inference-only access to Claude models.
# Cross-Region inference profile routes across US regions for availability.
data "aws_iam_policy_document" "ows_coda_bedrock_policy_document" {
  statement {
    sid    = "AllowBedrockModelInvoke"
    effect = "Allow"

    actions = [
      "bedrock:InvokeModel",
      "bedrock:InvokeModelWithResponseStream",
    ]

    resources = [
      "arn:aws:bedrock:us-*::foundation-model/anthropic.claude-opus-4-6-*",
      "arn:aws:bedrock:us-*:${data.aws_caller_identity.current.account_id}:inference-profile/us.anthropic.claude-opus-4-6-*",
      "arn:aws:bedrock:us-*::foundation-model/anthropic.claude-sonnet-4-6*",
      "arn:aws:bedrock:us-*:${data.aws_caller_identity.current.account_id}:inference-profile/us.anthropic.claude-sonnet-4-6*",
      "arn:aws:bedrock:us-*::foundation-model/anthropic.claude-haiku-4-5-*",
      "arn:aws:bedrock:us-*:${data.aws_caller_identity.current.account_id}:inference-profile/us.anthropic.claude-haiku-4-5-*"
    ]
  }
}

resource "aws_iam_policy" "ows_coda_bedrock_policy" {
  name        = "${var.environment}-${var.service_name}-bedrock-policy"
  description = "Allow ows-coda to invoke Bedrock models for the Coda chatbot"
  policy      = data.aws_iam_policy_document.ows_coda_bedrock_policy_document.json
}

resource "aws_iam_role_policy_attachment" "ows_coda_bedrock_policy_attachment" {
  role       = module.ows_coda_fargate_environment.fargate_task_iam_role_name
  policy_arn = aws_iam_policy.ows_coda_bedrock_policy.arn
}
