AWSTemplateFormatVersion: '2010-09-09'
Parameters:
  Name:
    Type: String
  DestinationEventBusArn:
    Type: String
    Description: Event bus ARN for the destination EventBridge bus

Resources:
  ProducerRule:
    Type: AWS::Events::Rule
    Properties:
      Name: !Sub 'rule-${Name}'
      Description: 'Config rule for producer'
      EventPattern:
        source:
          - aws.config
        detail-type:
          - Config Configuration Item Change
        detail:
          messageType:
            - ConfigurationItemChangeNotification
          configurationItem:
            resourceType:
              - '*'
      State: 'ENABLED'
      Targets:
        - Id: !Sub 'root-account-${Name}'
          Arn: !Ref DestinationEventBusArn
          RoleArn: !GetAtt ProducerRole.Arn
        - Id: !Sub 'log-${Name}'
          Arn: !GetAtt LogGroup.Arn

  LogGroup:
    DeletionPolicy: Retain
    UpdateReplacePolicy: Retain
    Type: AWS::Logs::LogGroup
    Properties:
      LogGroupName: !Sub '/aws/events/eventbridge/producer-${Name}'
      RetentionInDays: 7

  ProducerRole:
    Type: AWS::IAM::Role
    Properties:
      RoleName: !Sub 'role-producer-${Name}'
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal:
              Service: events.amazonaws.com
            Action: sts:AssumeRole
      Policies:
        - PolicyName: AllowEventsToEventBridge
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
              Effect: Allow
              Action:
                - events:PutEvents
              Resource: !Ref DestinationEventBusArn
        - PolicyName: AllowEventsToBeLogged
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
              Effect: Allow
              Action:
                - logs:CreateLogStream
                - logs:PutLogEvents
              Resource: '*'
