AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
  EmailCloudWatchDashboard

  Sample SAM Template for EmailCloudWatchDashboard

Globals:
  Function:
    Timeout: 3
    LoggingConfig:
      LogFormat: JSON

Resources:
  CloudwatchDashboardEmailSendFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: CloudwatchDashboardEmailSendFunction/
      Handler: app.lambda_handler
      Runtime: python3.12
      Timeout: 300
      Environment:
        Variables:
          # Parameter Store prefix - all parameters will be retrieved from this path
          # Example: /cloudwatch-dashboard-email/email_from
          PARAMETER_PREFIX: '/cloudwatch-dashboard-email'
          # Note: All configuration (email_from, email_to, email_subject, dashboard_name,
          # smtp_host, smtp_username, smtp_password) is now retrieved from Parameter Store
          # Create these parameters in AWS Systems Manager Parameter Store:
          # - /cloudwatch-dashboard-email/email_from (String)
          # - /cloudwatch-dashboard-email/email_to (String)
          # - /cloudwatch-dashboard-email/email_subject (String)
          # - /cloudwatch-dashboard-email/dashboard_name (String)
          # - /cloudwatch-dashboard-email/smtp_host (String)
          # - /cloudwatch-dashboard-email/smtp_username (String)
          # - /cloudwatch-dashboard-email/smtp_password (SecureString - encrypted)
      Architectures:
      - x86_64
      Policies:
        - AWSLambdaBasicExecutionRole
        - Statement:
          - Effect: Allow
            Action:
              - cloudwatch:GetDashboard
              - cloudwatch:GetMetricWidgetImage
            Resource: '*'
          - Effect: Allow
            Action:
              - ssm:GetParameter
              - ssm:GetParameters
            Resource: 
              - !Sub 'arn:aws:ssm:${AWS::Region}:${AWS::AccountId}:parameter/cloudwatch-dashboard-email/*'
      Events:
        MorningSchedule:
          Type: Schedule
          Properties:
            Schedule: cron(0 8 ? * * *)
        SendEmail:
          Type: Api
          Properties:
            Path: /hello
            Method: get

  ApplicationResourceGroup:
    Type: AWS::ResourceGroups::Group
    Properties:
      Name:
        Fn::Sub: ApplicationInsights-SAM-${AWS::StackName}
      ResourceQuery:
        Type: CLOUDFORMATION_STACK_1_0

  ApplicationInsightsMonitoring:
    Type: AWS::ApplicationInsights::Application
    Properties:
      ResourceGroupName:
        Ref: ApplicationResourceGroup
      AutoConfigurationEnabled: 'true'

Outputs:
  SendEmailApi:
    Description: API Gateway endpoint URL for Prod stage for Hello World function
    Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/"
  CloudwatchDashboardEmailSendFunction:
    Description: CloudwatchDashboardEmailSend Lambda Function ARN
    Value: !GetAtt CloudwatchDashboardEmailSendFunction.Arn