AWSTemplateFormatVersion: 2010-09-09
Transform: AWS::Serverless-2016-10-31

Parameters:
  BucketName:
    Type: String
    Default: saladeaula.digital
  UserTable:
    Type: String
    Default: betaeducacao-prod-users_d2o3r5gmm4it7j

Globals:
  Function:
    CodeUri: app/
    Runtime: python3.13
    Tracing: Active
    Architectures:
      - x86_64
    Layers:
      - !Sub arn:aws:lambda:sa-east-1:336641857101:layer:layercake:100
    Environment:
      Variables:
        TZ: America/Sao_Paulo
        LOG_LEVEL: DEBUG
        DYNAMODB_PARTITION_KEY: id
        POWERTOOLS_LOGGER_SAMPLE_RATE: 0.1
        POWERTOOLS_LOGGER_LOG_EVENT: true
        USER_TABLE: !Ref UserTable

Resources:
  EventLog:
    Type: AWS::Logs::LogGroup
    Properties:
      RetentionInDays: 90

  EventCsvIntoChunksFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: events.batch.csv_into_chunks.lambda_handler
      LoggingConfig:
        LogGroup: !Ref EventLog
      Policies:
        - DynamoDBCrudPolicy:
            TableName: !Ref UserTable
        - S3CrudPolicy:
            BucketName: !Ref BucketName
      Events:
        DynamoDBEvent:
          Type: EventBridgeRule
          Properties:
            Pattern:
              resources: [!Ref UserTable]
              detail:
                new_image:
                  id:
                    - prefix: BATCH_JOB#ORG#
                  sk:
                    - prefix: FILE#
                  status: [PENDING]

  EventChunksIntoUsersFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: events.batch.chunks_into_user.lambda_handler
      LoggingConfig:
        LogGroup: !Ref EventLog
      Policies:
        - DynamoDBCrudPolicy:
            TableName: !Ref UserTable
        - S3CrudPolicy:
            BucketName: !Ref BucketName
      Events:
        DynamoDBEvent:
          Type: EventBridgeRule
          Properties:
            Pattern:
              resources: [!Ref UserTable]
              detail:
                new_image:
                  id:
                    - prefix: BATCH_JOB#ORG#
                  sk:
                    - prefix: CHUNK#START#

  EventEmailReceivingFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: events.email_receiving.lambda_handler
      LoggingConfig:
        LogGroup: !Ref EventLog
      Policies:
        - DynamoDBCrudPolicy:
            TableName: !Ref UserTable

  LambdaInvokePermission:
    Type: AWS::Lambda::Permission
    Properties:
      FunctionName: !GetAtt EventEmailReceivingFunction.Arn
      Action: lambda:InvokeFunction
      Principal: ses.amazonaws.com
      SourceArn: !Sub arn:aws:ses:${AWS::Region}:${AWS::AccountId}:receipt-rule-set/*

  BucketPolicy:
    Type: AWS::S3::BucketPolicy
    Properties:
      Bucket: !Ref BucketName
      PolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Principal:
              Service: ses.amazonaws.com
            Action: s3:PutObject
            Resource: !Sub arn:aws:s3:::${BucketName}/*
            Condition:
              StringEquals:
                aws:SourceAccount: !Ref AWS::AccountId
              StringLike:
                aws:SourceArn: !Sub arn:aws:ses:${AWS::Region}:${AWS::AccountId}:receipt-rule-set/*

  EmailReceiptRuleSet:
    Type: AWS::SES::ReceiptRuleSet
    Properties:
      RuleSetName: users.noreply.saladeaula.digital

  EmailReceiptRule:
    Type: AWS::SES::ReceiptRule
    DependsOn:
      - LambdaInvokePermission
      - BucketPolicy
    Properties:
      RuleSetName: !Ref EmailReceiptRuleSet
      Rule:
        Name: lambda
        Enabled: true
        Actions:
          - LambdaAction:
              FunctionArn: !GetAtt EventEmailReceivingFunction.Arn
              InvocationType: RequestResponse
          - S3Action:
              BucketName: !Ref BucketName
              ObjectKeyPrefix: 'mailbox'
        ScanEnabled: true

  EventAddTenantFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: events.stopgap.add_tenant.lambda_handler
      Policies:
        - DynamoDBWritePolicy:
            TableName: !Ref UserTable
      LoggingConfig:
        LogGroup: !Ref EventLog
      Events:
        DynamoDBEvent:
          Type: EventBridgeRule
          Properties:
            Pattern:
              resources: [!Ref UserTable]
              detail:
                new_image:
                  id:
                    - prefix: orgmembers#

  EventSendWelcomeEmailFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: events.send_welcome_email.lambda_handler
      LoggingConfig:
        LogGroup: !Ref EventLog
      Policies:
        - Version: 2012-10-17
          Statement:
            - Effect: Allow
              Action:
                - ses:SendRawEmail
              Resource:
                - !Sub arn:aws:ses:${AWS::Region}:${AWS::AccountId}:identity/eduseg.com.br
                - !Sub arn:aws:ses:${AWS::Region}:${AWS::AccountId}:configuration-set/tracking
      Events:
        DynamoDBEvent:
          Type: EventBridgeRule
          Properties:
            Pattern:
              resources: [!Ref UserTable]
              detail-type: [INSERT]
              detail:
                new_image:
                  sk:
                    - prefix: EMAIL_VERIFICATION#
                  welcome:
                    - exists: true

  EventSendVerificationEmailFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: events.send_verification_email.lambda_handler
      LoggingConfig:
        LogGroup: !Ref EventLog
      Policies:
        - Version: 2012-10-17
          Statement:
            - Effect: Allow
              Action:
                - ses:SendRawEmail
              Resource:
                - !Sub arn:aws:ses:${AWS::Region}:${AWS::AccountId}:identity/eduseg.com.br
                - !Sub arn:aws:ses:${AWS::Region}:${AWS::AccountId}:configuration-set/tracking
      Events:
        DynamoDBEvent:
          Type: EventBridgeRule
          Properties:
            Pattern:
              resources: [!Ref UserTable]
              detail-type: [INSERT]
              detail:
                new_image:
                  sk:
                    - prefix: EMAIL_VERIFICATION#
                  welcome:
                    - exists: false

  EventCheckMxRecordFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: events.check_mx_record.lambda_handler
      LoggingConfig:
        LogGroup: !Ref EventLog
      Timeout: 12
      Policies:
        - DynamoDBCrudPolicy:
            TableName: !Ref UserTable
      Events:
        DynamoDBEvent:
          Type: EventBridgeRule
          Properties:
            Pattern:
              resources: [!Ref UserTable]
              detail-type: [INSERT]
              detail:
                new_image:
                  sk:
                    # Post-migration (users): rename `emails` to `EMAIL`
                    - prefix: emails#
                  mx_record_exists:
                    - exists: false

  EventUpdateAdminFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: events.update_admin.lambda_handler
      LoggingConfig:
        LogGroup: !Ref EventLog
      Policies:
        - DynamoDBCrudPolicy:
            TableName: !Ref UserTable
      Events:
        DynamoDBEvent:
          Type: EventBridgeRule
          Properties:
            Pattern:
              resources: [!Ref UserTable]
              detail-type: [MODIFY]
              detail:
                new_image:
                  sk: ['0']
                changes: [name, email, cpf]
