AWSTemplateFormatVersion: "2010-09-09"
Description: Gets expiry dates for digital subscriptions or emergency tokens

Parameters:
  Stack:
    Description: Stack name
    Type: String
    Default: subscriptions
  Stage:
    Description: Stage name
    Type: String
    AllowedValues:
        - PROD
        - CODE
    Default: CODE
  App:
    Description: App name
    Type: String
    AllowedValues:
      - digital-subscription-authorisation
    Default: digital-subscription-authorisation
Mappings:
  StageVariables:
    PROD:
      DomainName: 'digital-subscription-authorisation-prod.subscriptions.guardianapis.com'
      ApiGatewayTargetDomainName: 'd-6c6fh16i42.execute-api.eu-west-1.amazonaws.com'
    CODE:
      DomainName: 'digital-subscription-authorisation-code.subscriptions.guardianapis.com'
      ApiGatewayTargetDomainName: 'd-9hsw86gre3.execute-api.eu-west-1.amazonaws.com'
Resources:
    LambdaRole:
        Type: AWS::IAM::Role
        Properties:
            AssumeRolePolicyDocument:
                Statement:
                    - Effect: Allow
                      Principal:
                          Service:
                             - lambda.amazonaws.com
                      Action:
                          - sts:AssumeRole
            Path: /
            Policies:
                - PolicyName: LambdaPolicy
                  PolicyDocument:
                      Statement:
                          - Effect: Allow
                            Action:
                            - logs:CreateLogGroup
                            - logs:CreateLogStream
                            - logs:PutLogEvents
                            - lambda:InvokeFunction
                            Resource: !Sub "arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/lambda/digital-subscription-expiry-${Stage}:log-stream:*"
                - PolicyName: ReadPrivateCredentials
                  PolicyDocument:
                      Statement:
                          - Effect: Allow
                            Action: s3:GetObject
                            Resource:
                            - !Sub arn:aws:s3:::gu-reader-revenue-private/membership/support-service-lambdas/${Stage}/zuoraRest-${Stage}.*.json
                            - !Sub arn:aws:s3:::gu-reader-revenue-private/membership/support-service-lambdas/${Stage}/emergencyTokens-${Stage}.*.json
                            - !Sub arn:aws:s3:::gu-reader-revenue-private/membership/support-service-lambdas/${Stage}/trustedApi-${Stage}.*.json
    Lambda:
        Type: AWS::Lambda::Function
        Properties:
            Description: get digital subscription expiration dates
            FunctionName:
                !Sub digital-subscription-expiry-${Stage}
            Code:
                S3Bucket: subscriptions-dist
                S3Key: !Sub subscriptions/${Stage}/digital-subscription-expiry/digital-subscription-expiry.jar
            Handler: com.gu.digitalSubscriptionExpiry.Handler::apply
            Environment:
                Variables:
                  Stage: !Ref Stage
            Role:
                Fn::GetAtt:
                - "LambdaRole"
                - Arn
            MemorySize: 1536
            Runtime: java21
            Timeout: 300
            Architectures:
              - arm64
        DependsOn:
        - LambdaRole

    ApiGatewayLambdaPermission:
            Type: AWS::Lambda::Permission
            Properties:
                Action: lambda:invokeFunction
                FunctionName: !Sub digital-subscription-expiry-${Stage}
                Principal: apigateway.amazonaws.com
            DependsOn: Lambda

    ApiResource:
      Type: AWS::ApiGateway::Resource
      Properties:
        RestApiId: !Ref RestApi
        ParentId: !GetAtt [RestApi, RootResourceId]
        PathPart: subs
      DependsOn: RestApi

    ApiMethod:
      Type: AWS::ApiGateway::Method
      Properties:
        AuthorizationType: NONE
        RestApiId: !Ref RestApi
        ResourceId: !Ref ApiResource
        HttpMethod: POST
        Integration:
          Type: AWS_PROXY
          IntegrationHttpMethod: POST
          Uri: !Sub arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${Lambda.Arn}/invocations
      DependsOn:
        - RestApi
        - Lambda
        - ApiResource

    RestApi:
      Type: "AWS::ApiGateway::RestApi"
      Properties:
        Description: Api to handle digital sub authorisation
        Name: !Sub digital-sub-auth-handler-${Stage}

    RestApiStage:
      Type: AWS::ApiGateway::Stage
      Properties:
        Description: Stage for digital sub auth  API
        RestApiId: !Ref RestApi
        DeploymentId: !Ref RestApiDeployment
        StageName: !Sub ${Stage}
      DependsOn: ApiMethod

    RestApiDeployment:
      Type: AWS::ApiGateway::Deployment
      Properties:
        Description: Deploys the digital sub Auth API into an environment/stage
        RestApiId: !Ref RestApi
      DependsOn: ApiMethod

    DomainName:
      Type: "AWS::ApiGateway::DomainName"
      Properties:
        RegionalCertificateArn: !Sub arn:aws:acm:${AWS::Region}:${AWS::AccountId}:certificate/bece8c44-d92f-4661-a943-8b0b65e2ad6d
        DomainName: !FindInMap [StageVariables, !Ref 'Stage', DomainName]
        EndpointConfiguration:
          Types:
            - REGIONAL

    BasePathMapping:
      Type: "AWS::ApiGateway::BasePathMapping"
      Properties:
        RestApiId: !Ref RestApi
        DomainName: !Ref DomainName
        Stage: !Sub ${Stage}
      DependsOn: RestApiStage

    DNSRecord:
      Type: AWS::Route53::RecordSet
      Properties:
        HostedZoneName: subscriptions.guardianapis.com.
        Name: !Sub digital-subscription-authorisation-${Stage}.subscriptions.guardianapis.com.
        Comment: !Sub CNAME for digital subscription auth ${Stage}
        Type: CNAME
        TTL: '120'
        ResourceRecords:
          - !FindInMap [StageVariables, !Ref 'Stage', ApiGatewayTargetDomainName]

