# Security Hub account enablement ============================================

resource "aws_securityhub_account" "this" {
  auto_enable_controls      = var.auto_enable_controls
  control_finding_generator = var.control_finding_generator
}

# Delegated administrator ----------------------------------------------------

resource "aws_securityhub_organization_admin_account" "this" {
  count = var.enable_delegation && var.delegated_admin_account_id != null ? 1 : 0

  admin_account_id = var.delegated_admin_account_id

  depends_on = [aws_securityhub_account.this]
}

# Organization configuration -------------------------------------------------

resource "aws_securityhub_organization_configuration" "this" {
  count = var.enable_organization_config ? 1 : 0

  auto_enable           = var.auto_enable_org_members
  auto_enable_standards = var.auto_enable_org_members ? "DEFAULT" : "NONE"

  depends_on = [aws_securityhub_account.this]
}

# Security standards ---------------------------------------------------------

resource "aws_securityhub_standards_subscription" "this" {
  for_each = local.standard_arns

  standards_arn = each.value

  depends_on = [aws_securityhub_account.this]
}

# Disable specific controls --------------------------------------------------

resource "aws_securityhub_standards_control" "disabled" {
  for_each = local.disabled_control_map

  standards_control_arn = each.value.control_arn
  control_status        = "DISABLED"
  disabled_reason       = "Disabled via IaC configuration"

  depends_on = [aws_securityhub_standards_subscription.this]
}

# Finding aggregation --------------------------------------------------------

resource "aws_securityhub_finding_aggregator" "this" {
  for_each = var.finding_aggregation_region != null ? { agg = true } : {}

  linking_mode = "ALL_REGIONS"

  depends_on = [aws_securityhub_account.this]

  lifecycle {
    precondition {
      condition     = data.aws_region.current.name == var.finding_aggregation_region
      error_message = "The active AWS provider region (${data.aws_region.current.name}) must match the designated var.finding_aggregation_region (${var.finding_aggregation_region}) to configure finding aggregation."
    }
  }
}

# Member accounts ------------------------------------------------------------

resource "aws_securityhub_member" "this" {
  for_each = var.member_accounts

  account_id = each.value.account_id
  email      = each.value.email
  invite     = true

  depends_on = [aws_securityhub_account.this]
}
