AWSTemplateFormatVersion: '2010-09-09'
Description: Push Notifications reports extraction for the datalake
Parameters:
  Stack:
    Description: Stack name
    Type: String
  App:
    Description: Application name
    Type: String
  Stage:
    Description: Stage name
    Type: String
    AllowedValues:
      - CODE
      - PROD
  OutputBucket:
    Description: The ARN of the bucket to put the data in
    Type: String
  DeployBucket:
    Description: Bucket where RiffRaff uploads artifacts on deploy
    Type: String
Resources:
  Role:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Statement:
          - Effect: Allow
            Principal:
              Service:
                - lambda.amazonaws.com
            Action: sts:AssumeRole
      Path: /
      Policies:
        - PolicyName: logs
          PolicyDocument:
            Statement:
              Effect: Allow
              Action:
                - logs:CreateLogGroup
                - logs:CreateLogStream
                - logs:PutLogEvents
                - cloudwatch:putMetricData
              Resource:
                - !Sub arn:aws:logs:eu-west-1:${AWS::AccountId}:log-group:/aws/lambda/${Stack}-${App}-${Stage}:*
        - PolicyName: dynamo
          PolicyDocument:
            Statement:
              Effect: Allow
              Action:
                - dynamodb:GetItem
                - dynamodb:Query
              Resource:
                - !Sub arn:aws:dynamodb:${AWS::Region}:${AWS::AccountId}:table/mobile-notifications-reports-${Stage}
                - !Sub arn:aws:dynamodb:${AWS::Region}:${AWS::AccountId}:table/mobile-notifications-reports-${Stage}/index/sentTime-index
        - PolicyName: s3
          PolicyDocument:
            Statement:
              Effect: Allow
              Action:
                - s3:PutObjectAcl
                - s3:PutObject
              Resource:
                - !Ref OutputBucket
                - !Sub ${OutputBucket}/*
  Function:
    Type: AWS::Lambda::Function
    Properties:
      Code:
        S3Bucket: !Ref DeployBucket
        S3Key: !Sub ${Stack}/${Stage}/${App}/${App}.jar
      Description: Export sent notifications to the datalake
      Environment:
        Variables:
          Stage: !Ref Stage
          Stack: !Ref Stack
          App: !Ref App
      FunctionName: !Sub ${Stack}-${App}-${Stage}
      Handler: com.gu.notifications.extractor.Lambda
      MemorySize: 1024
      ReservedConcurrentExecutions: 1
      Role: !GetAtt Role.Arn
      Runtime: java11
      Timeout: 60
  EventRule:
    Type: AWS::Events::Rule
    Properties:
      ScheduleExpression: cron(0 1 1/1 * ? *)
      Targets:
        - Id: EventRuleTarget
          Arn: !GetAtt Function.Arn
  EventPermission:
    Type: AWS::Lambda::Permission
    Properties:
      FunctionName: !GetAtt Function.Arn
      Action: lambda:InvokeFunction
      Principal: events.amazonaws.com
      SourceArn: !GetAtt EventRule.Arn



