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
  EnrollmentTable:
    Type: String
    Default: betaeducacao-prod-enrollments
  CourseTable:
    Type: String
    Default: saladeaula_courses
  OrderTable:
    Type: String
    Default: betaeducacao-prod-orders

Globals:
  Function:
    CodeUri: app/
    Runtime: python3.13
    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
        ENROLLMENT_TABLE: !Ref EnrollmentTable
        ORDER_TABLE: !Ref OrderTable
        COURSE_TABLE: !Ref CourseTable
        BUCKET_NAME: !Ref BucketName
        POSTGRES_DB: saladeaula.digital
        POSTGRES_HOST: sp-node01.saladeaula.digital
        POSTGRES_PORT: 5432
        POSTGRES_USER: "{{resolve:ssm:/saladeaula/postgres_user}}"
        POSTGRES_PASSWORD: "{{resolve:ssm:/saladeaula/postgres_password}}"
        DOCUSEAL_KEY: "{{resolve:ssm:/saladeaula/docuseal_key}}"

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

  HttpLog:
    Type: AWS::Logs::LogGroup
    Properties:
      RetentionInDays: 90

  HttpApi:
    Type: AWS::Serverless::HttpApi
    Properties:
      CorsConfiguration:
        AllowOrigins: ["*"]
        AllowMethods: [POST, OPTIONS]
        AllowHeaders: [Content-Type, X-Requested-With]

  HttpApiFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: app.lambda_handler
      Timeout: 12
      LoggingConfig:
        LogGroup: !Ref HttpLog
      Policies:
        - DynamoDBWritePolicy:
            TableName: !Ref EnrollmentTable
        - S3WritePolicy:
            BucketName: !Ref BucketName
      Events:
        Post:
          Type: HttpApi
          Properties:
            Path: /
            Method: POST
            ApiId: !Ref HttpApi

  EventSetSubscriptionCoveredFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: events.stopgap.set_subscription_covered.lambda_handler
      LoggingConfig:
        LogGroup: !Ref EventLog
      Policies:
        - DynamoDBCrudPolicy:
            TableName: !Ref EnrollmentTable
        - DynamoDBReadPolicy:
            TableName: !Ref UserTable
      Events:
        DynamoDBEvent:
          Type: EventBridgeRule
          Properties:
            Pattern:
              resources: [!Ref EnrollmentTable]
              detail-type: [INSERT]
              detail:
                new_image:
                  sk: ["0"]
                  org_id:
                    - exists: true

  EventPatchCourseMetadataFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: events.stopgap.patch_course_metadata.lambda_handler
      LoggingConfig:
        LogGroup: !Ref EventLog
      Policies:
        - DynamoDBCrudPolicy:
            TableName: !Ref EnrollmentTable
        - DynamoDBCrudPolicy:
            TableName: !Ref CourseTable
      Events:
        DynamoDBEvent:
          Type: EventBridgeRule
          Properties:
            Pattern:
              resources: [!Ref EnrollmentTable]
              detail-type: [INSERT]
              detail:
                new_image:
                  sk: ["0"]
                  access_expires_at:
                    - exists: false

  EventPatchKonvivaFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: events.stopgap.patch_konviva.lambda_handler
      LoggingConfig:
        LogGroup: !Ref EventLog
      Policies:
        - DynamoDBWritePolicy:
            TableName: !Ref EnrollmentTable
        - DynamoDBReadPolicy:
            TableName: !Ref UserTable
        - DynamoDBReadPolicy:
            TableName: !Ref CourseTable
      Events:
        DynamoDBEvent:
          Type: EventBridgeRule
          Properties:
            Pattern:
              resources: [!Ref EnrollmentTable]
              detail-type: [INSERT]
              detail:
                new_image:
                  sk: ["0"]

  EventEnrollFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: events.enroll.lambda_handler
      LoggingConfig:
        LogGroup: !Ref EventLog
      Policies:
        - DynamoDBCrudPolicy:
            TableName: !Ref OrderTable
        - DynamoDBCrudPolicy:
            TableName: !Ref EnrollmentTable
        - DynamoDBReadPolicy:
            TableName: !Ref CourseTable
      Events:
        DynamoDBEvent:
          Type: EventBridgeRule
          Properties:
            Pattern:
              resources: [!Ref OrderTable]
              detail-type: [INSERT]
              detail:
                new_image:
                  # Post-migration: uncomment the following lines
                  # sk: [SLOT]
                  # mode: [STANDALONE]
                  sk: [generated_items]
                  scope: [SINGLE_USER]
                  status: [PENDING]

  EventReenrollIfFailedFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: events.reenroll_if_failed.lambda_handler
      LoggingConfig:
        LogGroup: !Ref EventLog
      Policies:
        - DynamoDBCrudPolicy:
            TableName: !Ref EnrollmentTable
      Events:
        DynamoDBEvent:
          Type: EventBridgeRule
          Properties:
            Pattern:
              resources: [!Ref EnrollmentTable]
              detail-type: [MODIFY]
              detail:
                changes: [status]
                new_image:
                  sk: ["0"]
                  status: [FAILED]
                  score:
                    - numeric: ["<", 70]
                old_image:
                  status: [IN_PROGRESS]

  EventAllocateSlotsFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: events.allocate_slots.lambda_handler
      LoggingConfig:
        LogGroup: !Ref EventLog
      Policies:
        - DynamoDBCrudPolicy:
            TableName: !Ref OrderTable
        - DynamoDBCrudPolicy:
            TableName: !Ref EnrollmentTable
        - DynamoDBReadPolicy:
            TableName: !Ref CourseTable
      Events:
        DynamoDBEvent:
          Type: EventBridgeRule
          Properties:
            Pattern:
              resources: [!Ref OrderTable]
              detail-type: [INSERT]
              detail:
                new_image:
                  # Post-migration: uncomment the following lines
                  # sk: [SLOT]
                  # mode: [BATCH]
                  sk: [generated_items]
                  scope: [MULTI_USER]
                  status: [PENDING]

  SesPolicy:
    Type: AWS::IAM::ManagedPolicy
    Properties:
      PolicyDocument:
        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

  EventSendReminderEmailsFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: events.send_reminder_emails.lambda_handler
      LoggingConfig:
        LogGroup: !Ref EventLog
      Policies:
        - !Ref SesPolicy
        - DynamoDBCrudPolicy:
            TableName: !Ref EnrollmentTable
      Events:
        DynamoDBEvent:
          Type: EventBridgeRule
          Properties:
            Pattern:
              resources: [!Ref EnrollmentTable]
              detail-type: [EXPIRE]
              detail:
                keys:
                  sk:
                    - SCHEDULE#REMINDER_NO_ACCESS_AFTER_3_DAYS
                    - SCHEDULE#REMINDER_NO_ACTIVITY_AFTER_7_DAYS
                    - SCHEDULE#REMINDER_ACCESS_PERIOD_BEFORE_30_DAYS
                    - SCHEDULE#REMINDER_CERT_EXPIRATION_BEFORE_30_DAYS

  EventScheduleRemindersFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: events.schedule_reminders.lambda_handler
      LoggingConfig:
        LogGroup: !Ref EventLog
      Policies:
        - DynamoDBCrudPolicy:
            TableName: !Ref EnrollmentTable
        - DynamoDBReadPolicy:
            TableName: !Ref CourseTable
      Events:
        DynamoDBEvent:
          Type: EventBridgeRule
          Properties:
            Pattern:
              resources: [!Ref EnrollmentTable]
              detail-type: [INSERT]
              detail:
                new_image:
                  sk: ["0"]
                  status: [PENDING]

  EventSetAccessExpiredFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: events.set_access_expired.lambda_handler
      LoggingConfig:
        LogGroup: !Ref EventLog
      Policies:
        - DynamoDBCrudPolicy:
            TableName: !Ref EnrollmentTable
      Events:
        DynamoDBEvent:
          Type: EventBridgeRule
          Properties:
            Pattern:
              resources: [!Ref EnrollmentTable]
              detail-type: [EXPIRE]
              detail:
                keys:
                  sk: [SCHEDULE#SET_ACCESS_EXPIRED, SCHEDULE#SET_AS_EXPIRED]

  EventSetCertExpiredFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: events.set_cert_expired.lambda_handler
      LoggingConfig:
        LogGroup: !Ref EventLog
      Policies:
        - DynamoDBCrudPolicy:
            TableName: !Ref EnrollmentTable
      Events:
        DynamoDBEvent:
          Type: EventBridgeRule
          Properties:
            Pattern:
              resources: [!Ref EnrollmentTable]
              detail-type: [EXPIRE]
              detail:
                keys:
                  sk: [SCHEDULE#SET_CERT_EXPIRED, SCHEDULE#SET_AS_ARCHIVED]

  EventIssueCertFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: events.issue_cert.lambda_handler
      Tracing: Active
      Timeout: 12
      LoggingConfig:
        LogGroup: !Ref EventLog
      Policies:
        - DynamoDBCrudPolicy:
            TableName: !Ref EnrollmentTable
        - DynamoDBReadPolicy:
            TableName: !Ref CourseTable
        - S3WritePolicy:
            BucketName: !Ref BucketName
      Events:
        DynamoDBEvent:
          Type: EventBridgeRule
          Properties:
            Pattern:
              resources: [!Ref EnrollmentTable]
              detail:
                keys:
                  sk: ["0"]
                new_image:
                  status: [COMPLETED]
                old_image:
                  status: [IN_PROGRESS]

  EventAskToSignFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: events.ask_to_sign.lambda_handler
      Tracing: Active
      Timeout: 12
      Policies:
        - S3ReadPolicy:
            BucketName: !Ref BucketName
      LoggingConfig:
        LogGroup: !Ref EventLog
      Events:
        DynamoDBEvent:
          Type: EventBridgeRule
          Properties:
            Pattern:
              resources: [!Ref EnrollmentTable]
              detail:
                keys:
                  sk: ["0"]
                new_image:
                  status: [COMPLETED]
                  cert:
                    s3_uri:
                      - exists: true
                old_image:
                  cert:
                    - exists: false

  EventReportingAppendCertFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: events.reporting.append_cert.lambda_handler
      LoggingConfig:
        LogGroup: !Ref EventLog
      Policies:
        - DynamoDBCrudPolicy:
            TableName: !Ref EnrollmentTable
      Events:
        DynamoDBEvent:
          Type: EventBridgeRule
          Properties:
            Pattern:
              resources: [!Ref EnrollmentTable]
              detail-type: [MODIFY]
              detail:
                keys:
                  sk: ["0"]
                new_image:
                  status: [COMPLETED]
                  cert_expires_at:
                    - exists: true
                  org_id:
                    - exists: true

  EventReportingSendReportEmailFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: events.reporting.send_report_email.lambda_handler
      Timeout: 12
      LoggingConfig:
        LogGroup: !Ref EventLog
      Policies:
        - DynamoDBCrudPolicy:
            TableName: !Ref EnrollmentTable
        - DynamoDBReadPolicy:
            TableName: !Ref UserTable
        - 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 EnrollmentTable]
              detail-type: [EXPIRE]
              detail:
                keys:
                  id:
                    - prefix: CERT_REPORTING#ORG
                  sk:
                    - suffix: SCHEDULE#SEND_REPORT_EMAIL

Outputs:
  HttpApiUrl:
    Description: URL of your API endpoint
    Value:
      Fn::Sub: "https://${HttpApi}.execute-api.${AWS::Region}.${AWS::URLSuffix}"
  HttpApiId:
    Description: Api ID of HttpApi
    Value:
      Ref: HttpApi
