Resources:
  Topic:
    Type: AWS::SNS::Topic
    Properties:
      Subscription:
      - Endpoint: !GetAtt 'InvokedFunction.Arn'
        Protocol: lambda

  TriggerFunction:
    Type: AWS::Serverless::Function
    Properties:
      Runtime: nodejs18.x
      Handler: index.handler
      Timeout: 10  # in case eb has delay
      InlineCode: |
        const {
                SNS
              } = require("@aws-sdk/client-sns"),
              {
                SQS
              } = require("@aws-sdk/client-sqs");
        exports.handler = async (event) => {
          var params = {
            Message: 'Test Message',
            TopicArn: process.env.TOPIC_ARN,
          };
          var sns = new SNS();
          var sqs = new SQS();
          await sns.publish(params);

          const data = await sqs.receiveMessage({
            QueueUrl: process.env.VERIFICATION_QUEUE_URL,
            WaitTimeSeconds: 5,
          });
          if (data.Messages.length == 0) {
            throw 'No messages in the queue!';
          }
        };
      Environment:
        Variables:
          TOPIC_ARN: !Ref Topic
          VERIFICATION_QUEUE_URL: !Ref VerificationQueue
          EVENT_SOURCE: !Sub '${AWS::StackName}-test-event'
      Policies:
      - SQSPollerPolicy:
          QueueName: !GetAtt VerificationQueue.QueueName

  InvokedFunction:
    Type: AWS::Serverless::Function
    Properties:
      Runtime: nodejs18.x
      Handler: index.handler
      InlineCode: |
        const {
          SQS
        } = require("@aws-sdk/client-sqs");
        exports.handler = async (event) => {
          const sqs = new SQS();
          await sqs.sendMessage({
            QueueUrl: process.env.VERIFICATION_QUEUE_URL,
            MessageBody: "test"
          });
        };
      Environment:
        Variables:
          VERIFICATION_QUEUE_URL: !Ref VerificationQueue
      Policies:
      - SQSSendMessagePolicy:
          QueueName: !GetAtt VerificationQueue.QueueName

  VerificationQueue:
    Type: AWS::SQS::Queue

  Connector:
    Type: AWS::Serverless::Connector
    Properties:
      Source:
        Id: Topic
      Destination:
        Id: InvokedFunction
      Permissions:
      - Write

  ConnectorNotTested:
    Type: AWS::Serverless::Connector
    Properties:
      Source:
        Id: TriggerFunction
      Destination:
        Id: Topic
      Permissions:
      - Write

Metadata:
  SamTransformTest: true
