# organization ===============================================================

resource "aws_organizations_organization" "this" {
  feature_set                   = var.feature_set
  aws_service_access_principals = var.aws_service_access_principals
  enabled_policy_types          = var.enabled_policy_types

  lifecycle {
    prevent_destroy = true
  }
}

# delegated administrators ---------------------------------------------------

resource "aws_organizations_delegated_administrator" "this" {
  for_each = var.delegated_administrators

  account_id        = each.value
  service_principal = each.key

  depends_on = [aws_organizations_organization.this]
}

# GuardDuty organization admin -------------------------------------------------
# Regional GuardDuty API: enables the delegated admin in the provider region
# after Organizations registration. Required before the delegated admin account
# can apply aws_guardduty_organization_configuration.

resource "aws_guardduty_organization_admin_account" "guardduty" {
  count = local.guardduty_delegated_admin_account_id != null ? 1 : 0

  admin_account_id = local.guardduty_delegated_admin_account_id

  depends_on = [
    aws_organizations_organization.this,
    aws_organizations_delegated_administrator.this,
  ]
}
