AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: Serverless finance staments analyzer using Textract and a serverless API

Conditions:
  CreateProdResources: !Equals
    - !Ref AWS::AccountId
    - 572540046516 # Dennis account ID (Production)

Globals:
  Function:
    Runtime: python3.7
    Handler: app.lambda_handler
    Architectures:
      - x86_64
    Timeout: 20
    MemorySize: 128
    Tracing: Active

Resources:
  S3Bucket:
    Type: AWS::S3::Bucket
    Properties:
      BucketName: !If
        - CreateProdResources
        - finance-parser-data
        - sandbox-finance-parser-data
      NotificationConfiguration:
        EventBridgeConfiguration:
          EventBridgeEnabled: true

  StateMachine:
    Type: AWS::Serverless::StateMachine
    Properties:
      Tracing:
        Enabled: true
      DefinitionUri: statemachine/statemachine.asl.json
      DefinitionSubstitutions:
        AnalyzeDocumentFunctionArn: !GetAtt AnalyzeDocumentFunction.Arn
        ProcessDocumentFunctionArn: !GetAtt ProcessDocumentFunction.Arn
        UploadDocumentFunctionArn: !GetAtt UploadDocumentFunction.Arn
      Events:
        StateChange:
          Type: EventBridgeRule
          Properties:
            Pattern:
              source:
                - aws.s3
              detail-type:
                - Object Created
              detail:
                bucket:
                  name:
                    - !Ref S3Bucket
                object:
                  key:
                    - "prefix": "unprocessed/"
    Connectors:
      StateMachineConnector:
        Properties:
          Destination:
            - Id: AnalyzeDocumentFunction
            - Id: ProcessDocumentFunction
            - Id: UploadDocumentFunction
          Permissions:
            - Write

  AnalyzeDocumentFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: analyze_document/
      Policies:
        - Version: "2012-10-17"
          Statement:
            - Effect: Allow
              Action:
                - textract:AnalyzeDocument
              Resource: "*"
    Connectors:
      S3Connector:
        Properties:
          Destination:
            Id: S3Bucket
          Permissions:
            - Read
            - Write

  ProcessDocumentFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: process_document/
    Connectors:
      S3Connector:
        Properties:
          Destination:
            Id: S3Bucket
          Permissions:
            - Read
            - Write

  UploadDocumentFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: upload_document/
    Connectors:
      DynamoConnector:
        Properties:
          Destination:
            Id: DynamoTable
          Permissions:
            - Write
      S3Connector:
        Properties:
          Destination:
            Id: S3Bucket
          Permissions:
            - Read

  Api:
    Type: AWS::Serverless::Api
    Properties:
      StageName: Prod
      Cors:
        AllowMethods: "'GET, POST, OPTIONS'"
        AllowHeaders: "'content-type, x-api-key'"
        AllowOrigin: "'*'"
      Models:
        Empty:
          type: object

  GetReportFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: get_report/
      Events:
        GetProductEvent:
          Type: Api
          Properties:
            RestApiId: !Ref Api
            Path: /report
            Method: get
            RequestParameters:
              - method.request.querystring.ticker:
                  Required: true
              - method.request.querystring.type:
                  Required: true
              - method.request.querystring.year:
                  Required: true
    Connectors:
      DynamoConnector:
        Properties:
          Destination:
            Id: DynamoTable
          Permissions:
            - Read

  GetTickersFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: get_tickers/
      Events:
        GetProductEvent:
          Type: Api
          Properties:
            RestApiId: !Ref Api
            Path: /tickers
            Method: get
    Connectors:
      DynamoConnector:
        Properties:
          Destination:
            Id: DynamoTable
          Permissions:
            - Read

  DynamoTable:
    Type: AWS::DynamoDB::Table
    Properties:
      TableName: FinanceParser
      BillingMode: PAY_PER_REQUEST
      DeletionProtectionEnabled: !If
        - CreateProdResources
        - True
        - False
      KeySchema:
        - AttributeName: pk
          KeyType: HASH
        - AttributeName: sk
          KeyType: RANGE
      AttributeDefinitions:
        - AttributeName: pk
          AttributeType: S
        - AttributeName: sk
          AttributeType: S

Outputs:
  GetReportEndpoint:
    Description: "Endpoint to get a report"
    Value: !Sub "https://${Api}.execute-api.${AWS::Region}.amazonaws.com/Prod/report"

  GetTickersEndpoint:
    Description: "Endpoint to get tickers"
    Value: !Sub "https://${Api}.execute-api.${AWS::Region}.amazonaws.com/Prod/ticker"

  RestApiId:
    Description: "The ID of the serverless rest API"
    Value: !Ref Api
    Export:
      Name: FinanceParserRestApiId
