AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: Fetch & analyse tweets using AWS Comprehend

# Global Settings
Globals:
  Function:
    Timeout: 3
    Tags:
      application-id: "tweet-analysis"
  Api:
    Auth:
      ApiKeyRequired: true
      UsagePlan:
        CreateUsagePlan: PER_API

Resources:
  # Create custom domain in Api Gateway
  Domain:
    Type: AWS::ApiGateway::DomainName
    Properties:
      RegionalCertificateArn: !Ref DomainCertificate
      DomainName: tweet-analysis.dennistech.io
      SecurityPolicy: TLS_1_2
      EndpointConfiguration:
        Types:
        - REGIONAL
      Tags:
        - Key: "application-id"
          Value: "tweet-analysis"
        - Key: "Name"
          Value: "tweet-analysis::api-custom-domain"

  # Create domain SSL certificate
  DomainCertificate:
    Type: AWS::CertificateManager::Certificate
    Properties:
      DomainName: tweet-analysis.dennistech.io
      ValidationMethod: DNS
      DomainValidationOptions:
        - DomainName: tweet-analysis.dennistech.io
          HostedZoneId: Z0937998E3C5GEK4NHO9
      Tags:
        - Key: "application-id"
          Value: "tweet-analysis"
        - Key: "Name"
          Value: "tweet-analysis::certificate::dennistech.io"

  # Map domain to the regional domain generated by Api Gateway
  DomainMapping:
    Type: AWS::Route53::RecordSet
    Properties:
      HostedZoneId: Z0937998E3C5GEK4NHO9
      Name: tweet-analysis.dennistech.io
      Type: A
      AliasTarget:
        DNSName: !GetAtt Domain.RegionalDomainName
        EvaluateTargetHealth: true
        HostedZoneId: !GetAtt Domain.RegionalHostedZoneId

  # Map paths from your domain name to your API stages
  PathMapping:
    Type: AWS::ApiGateway::BasePathMapping
    Properties:
      DomainName: !Ref Domain
      RestApiId: !Ref ServerlessRestApi
      Stage: Prod

  # Define lambda functions
  GetTweetSentimentFunction:
    Type: AWS::Serverless::Function
    Properties:
      Description: Fetch tweets and analyse sentiment using AWS Comprehend
      CodeUri: src/
      Handler: handlers/sentiment.get_tweet_sentiment
      Runtime: python3.9
      Tags:
        Name: "tweet-analysis::get-tweet-sentiment-function"
      Events:
        CallGetTweetSentiment:
          Type: Api
          Properties:
            Path: /sentiment
            Method: get
