AWSTemplateFormatVersion: "2010-09-09"
Description: >-
  26.06.10
  Flarelane CRM Event Export — cross-account IAM Role.
  Grants Flarelane permission to write exported CRM event data to your S3 bucket.
  Deploy this stack in the AWS account that owns the destination bucket.

Parameters:
  ProjectId:
    Type: String
    Description: Flarelane project ID (provided by Flarelane).
    AllowedPattern: "^[a-zA-Z0-9-]+$"

  DestinationBucketName:
    Type: String
    Description: Name of the S3 bucket that will receive exported data.
    AllowedPattern: "^[a-z0-9.-]{3,63}$"

  FlarelaneGlueRoleArn:
    Type: String
    Default: "arn:aws:iam::104605707706:role/production-crm-event-export-glue-role"
    Description: >-
      ARN of the Flarelane Glue job execution role that will assume this role.
      Use the default unless Flarelane instructs otherwise. The role name is
      fixed, so this value does not change across Flarelane deployments.
    AllowedPattern: "^arn:aws:iam::[0-9]{12}:role/.+$"

  KmsKeyArn:
    Type: String
    Default: ""
    Description: >-
      Optional. ARN of the KMS key used by the destination bucket's default
      encryption (SSE-KMS). Leave empty for SSE-S3 buckets.
      NOTE: Even with this parameter set, you must also add a Statement to the
      KMS key's Key Policy that allows this Role as a Principal — see the
      KmsKeyPolicyStatement output for the exact JSON to paste.
    AllowedPattern: "^$|^arn:aws:kms:[a-z0-9-]+:[0-9]{12}:key/.+$"

Conditions:
  HasKmsKey: !Not [!Equals [!Ref KmsKeyArn, ""]]

Resources:
  FlarelaneDeliveryRole:
    Type: AWS::IAM::Role
    Properties:
      RoleName: !Sub "flarelane-crm-export-${ProjectId}"
      Description: !Sub "Allows Flarelane to deliver CRM event exports to ${DestinationBucketName}."
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Principal:
              AWS: !Ref FlarelaneGlueRoleArn
            Action: sts:AssumeRole
            Condition:
              StringEquals:
                sts:ExternalId: !Ref ProjectId
      Policies:
        - PolicyName: FlarelaneS3DeliveryPolicy
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Effect: Allow
                Action:
                  # PutObject: Spark write
                  # GetObject: rename 단계에서 copy_object 가 source 를 읽을 때 필요
                  # DeleteObject: rename 후 part-XXXXX 원본 제거 + _SUCCESS 등 Spark 메타파일 정리,
                  # ListBucket: rename 단계의 list_objects_v2 페이지네이션
                  - s3:PutObject
                  - s3:GetObject
                  - s3:DeleteObject
                  - s3:ListBucket
                Resource:
                  - !Sub "arn:aws:s3:::${DestinationBucketName}"
                  - !Sub "arn:aws:s3:::${DestinationBucketName}/*"
        - !If
          - HasKmsKey
          - PolicyName: FlarelaneKmsPolicy
            PolicyDocument:
              Version: "2012-10-17"
              Statement:
                - Effect: Allow
                  Action:
                    # GenerateDataKey: PutObject 시 데이터 키 생성
                    # Decrypt: rename 단계에서 copy_object 가 source 를 읽을 때 필요
                    - kms:GenerateDataKey
                    - kms:Decrypt
                  Resource: !Ref KmsKeyArn
          - !Ref AWS::NoValue

Outputs:
  RoleArn:
    Description: Copy this ARN into your Flarelane project settings.
    Value: !GetAtt FlarelaneDeliveryRole.Arn

  KmsKeyPolicyStatement:
    Condition: HasKmsKey
    Description: >-
      ACTION REQUIRED: Add this Statement to your KMS key's Key Policy
      (KMS console → Customer managed keys → select key → Key policy → Edit).
      Without this, IAM permissions alone are not sufficient for cross-account
      KMS access.
    Value: !Sub |
      {
        "Sid": "AllowFlarelaneExportRole",
        "Effect": "Allow",
        "Principal": { "AWS": "${FlarelaneDeliveryRole.Arn}" },
        "Action": ["kms:GenerateDataKey", "kms:Decrypt"],
        "Resource": "*"
      }
