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

  Sample SAM Template for datafy

Parameters:
  VpcId:
    Type: AWS::EC2::VPC::Id
    Default: vpc-0ada1e5366ad5c132
    Description: VPC where Lambdas will run
  PrivateSubnet1Id:
    Type: AWS::EC2::Subnet::Id
    Default: subnet-0aa14f7bb45db8b87
    Description: First private subnet ID (with NAT egress)
  PrivateSubnet2Id:
    Type: AWS::EC2::Subnet::Id
    Default: subnet-0b651a99800a9d99e
    Description: Second private subnet ID (with NAT egress)

# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst
Globals:
  Function:
    Timeout: 900
    MemorySize: 1024
    EphemeralStorage:
      Size: 1536
    VpcConfig:
      SecurityGroupIds:
        - !Ref LambdaSecurityGroup
      SubnetIds:
        - !Ref PrivateSubnet1Id
        - !Ref PrivateSubnet2Id

    # You can add LoggingConfig parameters such as the Logformat, Log Group, and SystemLogLevel or ApplicationLogLevel. Learn more here https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-resource-function.html#sam-function-loggingconfig.
    LoggingConfig:
      LogFormat: JSON
Resources:
  LambdaSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: Egress-only security group for Lambda ENIs
      VpcId: !Ref VpcId
      SecurityGroupEgress:
        - IpProtocol: -1
          CidrIp: 0.0.0.0/0

  CommonPythonLayer:
    Type: AWS::Serverless::LayerVersion
    Properties:
      LayerName: datafy-common-python
      ContentUri: lambda_layer/
      CompatibleRuntimes:
        - python3.9
      RetentionPolicy: Retain
    Metadata:
      BuildMethod: python3.9

  ReadFiles:
    Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
    Properties:
      CodeUri: read_files/
      Handler: app.lambda_handler
      Runtime: python3.9
      Architectures:
      - x86_64
      Layers:
        - !Ref CommonPythonLayer
      Policies:
        - Version: '2012-10-17'
          Statement:
            - Effect: Allow
              Action:
                - lambda:InvokeFunction
                - ssm:GetParameter
              Resource: 
              - arn:aws:lambda:eu-west-1:587594388832:function:datafyNew-BatchUpdateSjreport-utMCtdWkdNo8
              - arn:aws:ssm:eu-west-1:587594388832:parameter/supabase/url   
              - arn:aws:ssm:eu-west-1:587594388832:parameter/supabase/anon   
              - arn:aws:ssm:eu-west-1:587594388832:parameter/gmail/username
              - arn:aws:ssm:eu-west-1:587594388832:parameter/gmail/app_password
              - arn:aws:ssm:eu-west-1:587594388832:parameter/gmail/to_emails
              - arn:aws:ssm:eu-west-1:587594388832:parameter/gmail/to_emails_client      

  CreateCombinedWeeklyReport:
      Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
      Properties:
        CodeUri: create_combined_weekly_report/
        Handler: app.lambda_handler
        Runtime: python3.9
        Architectures:
        - x86_64
        Layers:
          - !Ref CommonPythonLayer
        Policies:
          - Version: '2012-10-17'
            Statement:
              - Effect: Allow
                Action:
                  - lambda:InvokeFunction
                  - ssm:GetParameter
                Resource: 
                - arn:aws:ssm:eu-west-1:587594388832:parameter/supabase/url   
                - arn:aws:ssm:eu-west-1:587594388832:parameter/supabase/anon
                - arn:aws:ssm:eu-west-1:587594388832:parameter/supabase/service_role
                - arn:aws:ssm:eu-west-1:587594388832:parameter/gmail/username
                - arn:aws:ssm:eu-west-1:587594388832:parameter/gmail/app_password
                - arn:aws:ssm:eu-west-1:587594388832:parameter/gmail/to_emails
                - arn:aws:ssm:eu-west-1:587594388832:parameter/gmail/to_emails_client
        Events:
          CreateCombinedWeeklyReportApi:
            Type: Api
            Properties:
              Path: /generate-combined-week-report
              Method: post
              RestApiId: !Ref ReadFilesApi
          CreateCombinedWeeklyReportOptions:
            Type: Api
            Properties:
              Path: /generate-combined-week-report
              Method: options
              RestApiId: !Ref ReadFilesApi
          CreateCombinedWeeklyReportDailySchedule:
            Type: Schedule
            Properties:
              # 03:00 UTC == 05:00 South Africa Standard Time (UTC+2)
              Schedule: cron(0 3 * * ? *)
              # Mark this as a cron run so the Lambda sends the report link email
              Input: '{"customer_id": 1,"is_cron": true}'

  CreateKachingDailyReport:
      Type: AWS::Serverless::Function # Kaching Daily Report (no API, cron-only)
      Properties:
        CodeUri: create_kaching_daily_report/
        Handler: app.lambda_handler
        Runtime: python3.9
        Architectures:
        - x86_64
        Layers:
          - !Ref CommonPythonLayer
        Policies:
          - Version: '2012-10-17'
            Statement:
              - Effect: Allow
                Action:
                  - lambda:InvokeFunction
                  - ssm:GetParameter
                Resource: 
                - arn:aws:ssm:eu-west-1:587594388832:parameter/supabase/url   
                - arn:aws:ssm:eu-west-1:587594388832:parameter/supabase/anon   
                - arn:aws:ssm:eu-west-1:587594388832:parameter/gmail/username
                - arn:aws:ssm:eu-west-1:587594388832:parameter/gmail/app_password
                - arn:aws:ssm:eu-west-1:587594388832:parameter/gmail/to_emails
                - arn:aws:ssm:eu-west-1:587594388832:parameter/gmail/to_emails_client
        Events:
          CreateKachingDailyReportDailySchedule:
            Type: Schedule
            Properties:
              # 03:00 UTC == 05:00 South Africa Standard Time (UTC+2)
              # Runs Kaching Daily Report once a day (cron-only Lambda, always emails on success)
              Schedule: cron(0 3 * * ? *)
              Input: '{"customer_id": 1}'

  ReadPromosKaching:
    Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
    Properties:
      CodeUri: read_promo_kaching/
      Handler: app.lambda_handler
      Runtime: python3.9
      Architectures:
      - x86_64
      Layers:
        - !Ref CommonPythonLayer
      Policies:
      - Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Action:
              - ssm:GetParameter
            Resource:             
            - arn:aws:ssm:eu-west-1:587594388832:parameter/supabase/url   
            - arn:aws:ssm:eu-west-1:587594388832:parameter/supabase/anon 
            - arn:aws:ssm:eu-west-1:587594388832:parameter/gmail/username
            - arn:aws:ssm:eu-west-1:587594388832:parameter/gmail/app_password
            - arn:aws:ssm:eu-west-1:587594388832:parameter/gmail/to_emails
            - arn:aws:ssm:eu-west-1:587594388832:parameter/gmail/to_emails_client 
      # Events:
        # ReadPromoScheduler: # Added scheduler event
          # Type: Schedule
          # Properties:
          #   Schedule: rate(1 minute) # Trigger every minute
          #   Input: '{}' # You can provide input JSON for the event here if needed  
        # ReadPromosKachingApi:
        #   Type: Api
        #   Properties:
        #     Path: /read-promos-kaching
        #     Method: post
        #     RestApiId: !Ref ReadFilesApi
        # ReadPromosKachingOptions:
        #   Type: Api
        #   Properties:
        #     Path: /read-promos-kaching
        #     Method: options
        #     RestApiId: !Ref ReadFilesApi

  # S3 bucket for create_tasks batch payloads (staging); batches are processed by Step Function then can be expired
  CreateTasksStagingBucket:
    Type: AWS::S3::Bucket
    Properties:
      LifecycleConfiguration:
        Rules:
          - Id: ExpireBatchFiles
            Status: Enabled
            ExpirationInDays: 1
            Prefix: batches/

  CreateTasks:
    Type: AWS::Serverless::Function # Original: fetch+transform+insert in-process (use for normal runs)
    Properties:
      CodeUri: create_tasks/
      Handler: app.lambda_handler
      Runtime: python3.9
      Architectures:
      - x86_64
      Layers:
        - !Ref CommonPythonLayer
      Policies:
      - Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Action:
              - lambda:InvokeFunction
              - ssm:GetParameter
            Resource:
              - arn:aws:lambda:eu-west-1:587594388832:function:datafyNew-StartProcessQueue-r6W4pr83cx2y
              - arn:aws:ssm:eu-west-1:587594388832:parameter/supabase/url
              - arn:aws:ssm:eu-west-1:587594388832:parameter/supabase/anon
              - arn:aws:ssm:eu-west-1:587594388832:parameter/gmail/username
              - arn:aws:ssm:eu-west-1:587594388832:parameter/gmail/app_password
              - arn:aws:ssm:eu-west-1:587594388832:parameter/gmail/to_emails
              - arn:aws:ssm:eu-west-1:587594388832:parameter/gmail/to_emails_client

  # Bulk path: fetch+transform, write batches to S3, start Step Function (use when 34k+ tasks to avoid timeout)
  CreateTasksBulk:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: create_tasks_bulk/
      Handler: app.lambda_handler
      Runtime: python3.9
      Architectures:
      - x86_64
      Layers:
        - !Ref CommonPythonLayer
      Environment:
        Variables:
          CREATE_TASKS_STAGING_BUCKET: !Ref CreateTasksStagingBucket
          CREATE_TASKS_STATE_MACHINE_ARN: !Ref CreateTasksWorkflow
          CREATE_TASKS_FINALIZE_ARN: !GetAtt CreateTasksFinalize.Arn
      Policies:
      - Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Action:
              - ssm:GetParameter
              - s3:PutObject
              - s3:DeleteObject
              - states:StartExecution
              - lambda:InvokeFunction
            Resource:
              - arn:aws:ssm:eu-west-1:587594388832:parameter/supabase/url
              - arn:aws:ssm:eu-west-1:587594388832:parameter/supabase/anon
              - arn:aws:ssm:eu-west-1:587594388832:parameter/gmail/username
              - arn:aws:ssm:eu-west-1:587594388832:parameter/gmail/app_password
              - arn:aws:ssm:eu-west-1:587594388832:parameter/gmail/to_emails
              - arn:aws:ssm:eu-west-1:587594388832:parameter/gmail/to_emails_client
              - !Sub 'arn:aws:s3:::${CreateTasksStagingBucket}'
              - !Sub 'arn:aws:s3:::${CreateTasksStagingBucket}/*'
              - !Ref CreateTasksWorkflow
              - !GetAtt CreateTasksFinalize.Arn
          - Effect: Allow
            Action: s3:ListBucket
            Resource: !Sub 'arn:aws:s3:::${CreateTasksStagingBucket}'

  CreateTasksListBatches:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: create_tasks_list_batches/
      Handler: app.lambda_handler
      Runtime: python3.9
      Architectures:
      - x86_64
      Layers:
        - !Ref CommonPythonLayer
      Environment:
        Variables:
          CREATE_TASKS_STAGING_BUCKET: !Ref CreateTasksStagingBucket
      Policies:
      - Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Action: s3:ListBucket
            Resource: !Sub 'arn:aws:s3:::${CreateTasksStagingBucket}'
          - Effect: Allow
            Action: s3:GetObject
            Resource: !Sub 'arn:aws:s3:::${CreateTasksStagingBucket}/*'

  InsertTasksBatch:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: insert_tasks_batch/
      Handler: app.lambda_handler
      Runtime: python3.9
      Timeout: 300
      MemorySize: 512
      Architectures:
      - x86_64
      Layers:
        - !Ref CommonPythonLayer
      Policies:
      - Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Action:
              - ssm:GetParameter
              - s3:GetObject
            Resource:
              - arn:aws:ssm:eu-west-1:587594388832:parameter/supabase/url
              - arn:aws:ssm:eu-west-1:587594388832:parameter/supabase/anon
              - !Sub 'arn:aws:s3:::${CreateTasksStagingBucket}/*'

  CreateTasksFinalize:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: create_tasks_finalize/
      Handler: app.lambda_handler
      Runtime: python3.9
      Architectures:
      - x86_64
      Layers:
        - !Ref CommonPythonLayer
      Environment:
        Variables:
          START_PROCESS_QUEUE_ARN: !GetAtt StartProcessQueue.Arn
      Policies:
      - Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Action:
              - lambda:InvokeFunction
              - ssm:GetParameter
            Resource:
              - !GetAtt StartProcessQueue.Arn
              - arn:aws:ssm:eu-west-1:587594388832:parameter/supabase/url
              - arn:aws:ssm:eu-west-1:587594388832:parameter/supabase/anon
              - arn:aws:ssm:eu-west-1:587594388832:parameter/gmail/username
              - arn:aws:ssm:eu-west-1:587594388832:parameter/gmail/app_password
              - arn:aws:ssm:eu-west-1:587594388832:parameter/gmail/to_emails
              - arn:aws:ssm:eu-west-1:587594388832:parameter/gmail/to_emails_client

  CreateTasksWorkflow:
    Type: AWS::StepFunctions::StateMachine
    Properties:
      StateMachineName: !Sub '${AWS::StackName}-CreateTasks'
      RoleArn: !GetAtt CreateTasksWorkflowRole.Arn
      DefinitionString: !Sub
        - |
          {"Comment":"List batches then insert and finalize","StartAt":"PrepareBatches","States":{"PrepareBatches":{"Type":"Task","Resource":"arn:aws:states:::lambda:invoke","OutputPath":"$.Payload","Parameters":{"FunctionName":"${CreateTasksListBatchesArn}","Payload.$":"$"},"Next":"InsertBatches"},"InsertBatches":{"Type":"Map","ItemsPath":"$.items","ResultPath":"$.insert_results","MaxConcurrency":1,"ItemProcessor":{"ProcessorConfig":{"Mode":"INLINE"},"StartAt":"InsertOneBatch","States":{"InsertOneBatch":{"Type":"Task","Resource":"arn:aws:states:::lambda:invoke","OutputPath":"$.Payload","Parameters":{"FunctionName":"${InsertTasksBatchArn}","Payload.$":"$"},"Retry":[{"ErrorEquals":["Lambda.ServiceException","Lambda.AWSLambdaException","Lambda.SdkClientException","Lambda.TooManyRequestsException"],"IntervalSeconds":2,"MaxAttempts":3,"BackoffRate":2}],"End":true}}},"Next":"Finalize"},"Finalize":{"Type":"Task","Resource":"arn:aws:states:::lambda:invoke","OutputPath":"$.Payload","Parameters":{"FunctionName":"${CreateTasksFinalizeArn}","Payload":{"week_start_date.$":"$.week_start_date"}},"End":true}}}
        - CreateTasksListBatchesArn: !GetAtt CreateTasksListBatches.Arn
          InsertTasksBatchArn: !GetAtt InsertTasksBatch.Arn
          CreateTasksFinalizeArn: !GetAtt CreateTasksFinalize.Arn

  CreateTasksWorkflowRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal:
              Service: states.amazonaws.com
            Action: sts:AssumeRole
      ManagedPolicyArns:
        - !Ref CreateTasksWorkflowPolicy

  CreateTasksWorkflowPolicy:
    Type: AWS::IAM::ManagedPolicy
    Properties:
      PolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Action: lambda:InvokeFunction
            Resource:
              - !GetAtt CreateTasksListBatches.Arn
              - !GetAtt InsertTasksBatch.Arn
              - !GetAtt CreateTasksFinalize.Arn

  BatchUpdateSjreport:
    Type: AWS::Serverless::Function # Invokes CreateTasksBulk after batch update
    Properties:
      CodeUri: batch_update_sjreport/
      Handler: app.lambda_handler
      Runtime: python3.9
      Architectures:
      - x86_64
      Layers:
        - !Ref CommonPythonLayer
      Environment:
        Variables:
          CREATE_TASKS_BULK_ARN: !GetAtt CreateTasksBulk.Arn
      Policies:
      - Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Action:
              - lambda:InvokeFunction
              - ssm:GetParameter
            Resource:
              - !GetAtt CreateTasksBulk.Arn
              - arn:aws:ssm:eu-west-1:587594388832:parameter/supabase/url
              - arn:aws:ssm:eu-west-1:587594388832:parameter/supabase/anon
              - arn:aws:ssm:eu-west-1:587594388832:parameter/gmail/username
              - arn:aws:ssm:eu-west-1:587594388832:parameter/gmail/app_password
              - arn:aws:ssm:eu-west-1:587594388832:parameter/gmail/to_emails
              - arn:aws:ssm:eu-west-1:587594388832:parameter/gmail/to_emails_client  

  UpdateStoreIssues:
    Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
    Properties:
      CodeUri: update_store_issues/
      Handler: app.lambda_handler
      Runtime: python3.9
      Architectures:
      - x86_64
      Layers:
        - !Ref CommonPythonLayer
      Policies:
      - Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Action:
              - ssm:GetParameter
            Resource:             
            - arn:aws:ssm:eu-west-1:587594388832:parameter/supabase/url   
            - arn:aws:ssm:eu-west-1:587594388832:parameter/supabase/anon 
            - arn:aws:ssm:eu-west-1:587594388832:parameter/gmail/username
            - arn:aws:ssm:eu-west-1:587594388832:parameter/gmail/app_password
            - arn:aws:ssm:eu-west-1:587594388832:parameter/gmail/to_emails
            - arn:aws:ssm:eu-west-1:587594388832:parameter/gmail/to_emails_client

  UpdateTaskIssues:
    Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
    Properties:
      CodeUri: update_task_issues/
      Handler: app.lambda_handler
      Runtime: python3.9
      Architectures:
      - x86_64
      Layers:
        - !Ref CommonPythonLayer
      Policies:
      - Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Action:
              - ssm:GetParameter
            Resource:             
            - arn:aws:ssm:eu-west-1:587594388832:parameter/supabase/url   
            - arn:aws:ssm:eu-west-1:587594388832:parameter/supabase/anon 
            - arn:aws:ssm:eu-west-1:587594388832:parameter/gmail/username
            - arn:aws:ssm:eu-west-1:587594388832:parameter/gmail/app_password
            - arn:aws:ssm:eu-west-1:587594388832:parameter/gmail/to_emails
            - arn:aws:ssm:eu-west-1:587594388832:parameter/gmail/to_emails_client

  BackupSjreport:
    Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
    Properties:
      CodeUri: backup_sjreport/
      Handler: app.lambda_handler
      Runtime: python3.9
      Architectures:
      - x86_64
      Layers:
        - !Ref CommonPythonLayer
      Environment:
        Variables:
          CLEAR_SJREPORT_OLD_DATA_ARN: !GetAtt SJReportClearOldData.Arn    
      Policies:
      - Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Action:
              - lambda:InvokeFunction
              - ssm:GetParameter
            Resource:        
            - !GetAtt SJReportClearOldData.Arn       
            - arn:aws:ssm:eu-west-1:587594388832:parameter/supabase/url   
            - arn:aws:ssm:eu-west-1:587594388832:parameter/supabase/anon 
            - arn:aws:ssm:eu-west-1:587594388832:parameter/gmail/username
            - arn:aws:ssm:eu-west-1:587594388832:parameter/gmail/app_password
            - arn:aws:ssm:eu-west-1:587594388832:parameter/gmail/to_emails
            - arn:aws:ssm:eu-west-1:587594388832:parameter/gmail/to_emails_client

  SJReportClearOldData:
    Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
    Properties:
      CodeUri: sjreport_clear_old_data/
      Handler: app.lambda_handler
      Runtime: python3.9
      Architectures:
      - x86_64
      Layers:
        - !Ref CommonPythonLayer
      Environment:
        Variables:
          BACKUP_TASKS_ARN: !GetAtt BackupTasks.Arn 
      Policies:
      - Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Action:
              - lambda:InvokeFunction
              - ssm:GetParameter
            Resource:       
            - !GetAtt BackupTasks.Arn
            - arn:aws:ssm:eu-west-1:587594388832:parameter/supabase/url   
            - arn:aws:ssm:eu-west-1:587594388832:parameter/supabase/anon 
            - arn:aws:ssm:eu-west-1:587594388832:parameter/gmail/username
            - arn:aws:ssm:eu-west-1:587594388832:parameter/gmail/app_password
            - arn:aws:ssm:eu-west-1:587594388832:parameter/gmail/to_emails
            - arn:aws:ssm:eu-west-1:587594388832:parameter/gmail/to_emails_client

  BackupTasks:
    Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
    Properties:
      CodeUri: backup_tasks/
      Handler: app.lambda_handler
      Runtime: python3.9
      Architectures:
      - x86_64
      Layers:
        - !Ref CommonPythonLayer
      Environment:
        Variables:
          CLEAR_TASKS_OLD_DATA_ARN: !GetAtt TasksClearOldData.Arn    
      Policies:
      - Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Action:
              - lambda:InvokeFunction
              - ssm:GetParameter
            Resource:        
            - !GetAtt TasksClearOldData.Arn       
            - arn:aws:ssm:eu-west-1:587594388832:parameter/supabase/url   
            - arn:aws:ssm:eu-west-1:587594388832:parameter/supabase/anon 
            - arn:aws:ssm:eu-west-1:587594388832:parameter/gmail/username
            - arn:aws:ssm:eu-west-1:587594388832:parameter/gmail/app_password
            - arn:aws:ssm:eu-west-1:587594388832:parameter/gmail/to_emails
            - arn:aws:ssm:eu-west-1:587594388832:parameter/gmail/to_emails_client

  TasksClearOldData:
    Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
    Properties:
      CodeUri: task_clear_old_data/
      Handler: app.lambda_handler
      Runtime: python3.9
      Architectures:
      - x86_64
      Layers:
        - !Ref CommonPythonLayer
      Policies:
      - Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Action:
              - ssm:GetParameter
            Resource:             
            - arn:aws:ssm:eu-west-1:587594388832:parameter/supabase/url   
            - arn:aws:ssm:eu-west-1:587594388832:parameter/supabase/anon 
            - arn:aws:ssm:eu-west-1:587594388832:parameter/gmail/username
            - arn:aws:ssm:eu-west-1:587594388832:parameter/gmail/app_password
            - arn:aws:ssm:eu-west-1:587594388832:parameter/gmail/to_emails
            - arn:aws:ssm:eu-west-1:587594388832:parameter/gmail/to_emails_client

  StartProcessQueue:
    Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
    Properties:
      CodeUri: start_process_queue/
      Handler: app.lambda_handler
      Runtime: python3.9
      Architectures:
      - x86_64
      Layers:
        - !Ref CommonPythonLayer
      Environment:
        Variables:
          BACKUP_SJREPORT_ARN: !GetAtt BackupSjreport.Arn
      Policies:
      - Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Action:
              - lambda:InvokeFunction
              - ssm:GetParameter
            Resource:       
            - !GetAtt BackupSjreport.Arn
            - arn:aws:ssm:eu-west-1:587594388832:parameter/supabase/url   
            - arn:aws:ssm:eu-west-1:587594388832:parameter/supabase/anon 
            - arn:aws:ssm:eu-west-1:587594388832:parameter/gmail/username
            - arn:aws:ssm:eu-west-1:587594388832:parameter/gmail/app_password
            - arn:aws:ssm:eu-west-1:587594388832:parameter/gmail/to_emails
            - arn:aws:ssm:eu-west-1:587594388832:parameter/gmail/to_emails_client


  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'

  ReadFilesApi:
    Type: AWS::Serverless::Api
    Properties:
      StageName: prod
      Cors:
        AllowMethods: "'POST,OPTIONS'"
        AllowHeaders: "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'"
        AllowOrigin: "'*'"

  TriggerReadFiles:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: trigger_read_files/
      Handler: app.lambda_handler
      Runtime: python3.9
      Architectures:
        - x86_64
      Layers:
        - !Ref CommonPythonLayer
      Environment:
        Variables:
          READ_FILES_ARN: !GetAtt ReadFiles.Arn
      Policies:
        - Version: '2012-10-17'
          Statement:
            - Effect: Allow
              Action:
                - lambda:InvokeFunction
                - ssm:GetParameter
              Resource: 
                - !GetAtt ReadFiles.Arn
                - arn:aws:ssm:eu-west-1:587594388832:parameter/gmail/username
                - arn:aws:ssm:eu-west-1:587594388832:parameter/gmail/app_password
                - arn:aws:ssm:eu-west-1:587594388832:parameter/gmail/to_emails
                - arn:aws:ssm:eu-west-1:587594388832:parameter/gmail/to_emails_client
      Events:
        TriggerReadFilesApi:
          Type: Api
          Properties:
            Path: /trigger-read-files
            Method: post
            RestApiId: !Ref ReadFilesApi
        TriggerReadFilesOptions:
          Type: Api
          Properties:
            Path: /trigger-read-files
            Method: options
            RestApiId: !Ref ReadFilesApi

  TriggerReadPromosKaching:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: trigger_read_promos_kaching/
      Handler: app.lambda_handler
      Runtime: python3.9
      Architectures:
        - x86_64
      Layers:
        - !Ref CommonPythonLayer
      Environment:
        Variables:
          READ_PROMOS_KACHING_ARN: !GetAtt ReadPromosKaching.Arn
      Policies:
        - Version: '2012-10-17'
          Statement:
            - Effect: Allow
              Action:
                - lambda:InvokeFunction
                - ssm:GetParameter
              Resource: 
                - !GetAtt ReadPromosKaching.Arn
                - arn:aws:ssm:eu-west-1:587594388832:parameter/gmail/username
                - arn:aws:ssm:eu-west-1:587594388832:parameter/gmail/app_password
                - arn:aws:ssm:eu-west-1:587594388832:parameter/gmail/to_emails
                - arn:aws:ssm:eu-west-1:587594388832:parameter/gmail/to_emails_client
      Events:
        TriggerReadPromosKachingApi:
          Type: Api
          Properties:
            Path: /trigger-read-promos-kaching
            Method: post
            RestApiId: !Ref ReadFilesApi
        TriggerReadPromosKachingOptions:
          Type: Api
          Properties:
            Path: /trigger-read-promos-kaching
            Method: options
            RestApiId: !Ref ReadFilesApi

# Outputs:
  # ServerlessRestApi is an implicit API created out of Events key under Serverless::Function
  # Find out more about other implicit resources you can reference within SAM
  # https://github.com/awslabs/serverless-application-model/blob/master/docs/internals/generated_resources.rst#api
  # HelloWorldApi:
  #   Description: API Gateway endpoint URL for Prod stage for Hello World function
  #   Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/"
  # HelloWorldFunction:
  #   Description: Hello World Lambda Function ARN
  #   Value: !GetAtt HelloWorldFunction.Arn
  # HelloWorldFunctionIamRole:
  #   Description: Implicit IAM Role created for Hello World function
  #   Value: !GetAtt HelloWorldFunctionRole.Arn
