---
AWSTemplateFormatVersion: '2010-09-09'
Description: ApirateLimit link Account Setup

Parameters:
  DataCollectionAccountID:
    Type: String
    Description: AccountId of data Collection Account
  DataCollectionRegion:
    Type: String
    Description: Account Region of of data Collection Account
  ErrorCodeFilter:
    Type: String
    Description: Comma-separated list of errorCode values to filter. Include any additional errorCode patterns to filter.
    Default: "Client.RequestLimitExceeded,ThrottlingException"
  ResourcePrefix:
    Type: String
    Description: This prefix will be placed in front of resources created where required. Note you may wish to add a dash at the end to make more readable
    Default: "ApiRateLimit-"

    
Resources:
  DataCollectionRuleRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Principal:
              Service: events.amazonaws.com
            Action: sts:AssumeRole
      Path: "/"
      Policies:
        - PolicyName: !Sub "ApiRateLimitPutEvent-${AWS::AccountId}-${AWS::Region}-Policy"
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Effect: Allow
                Action: "events:PutEvents"
                Resource: 
                  - !Sub "arn:${AWS::Partition}:events:${DataCollectionRegion}:${DataCollectionAccountID}:event-bus/${ResourcePrefix}DataCollectionBus-${DataCollectionAccountID}"

  DefaultBusRuleApirateLimit:
    Type: "AWS::Events::Rule"
    Properties:
      Description: "EventBridge default rule for throttling events"
      EventBusName: "default"
      EventPattern: 
        detail-type:
          - "AWS API Call via CloudTrail"
        detail:
          errorCode: 
            !Split [",", !Ref ErrorCodeFilter]
      Targets:
        - Arn: !Sub "arn:${AWS::Partition}:events:${DataCollectionRegion}:${DataCollectionAccountID}:event-bus/${ResourcePrefix}DataCollectionBus-${DataCollectionAccountID}"
          Id: DataCollectionRuleOnDefaultBus
          RoleArn: !GetAtt  DataCollectionRuleRole.Arn