AWSTemplateFormatVersion: '2010-09-09'
Description: Lambda que se dispara automáticamente al subir archivos a un bucket de S3

Resources:
  # ==================== ROL IAM ====================
  LambdaExecutionRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal:
              Service: lambda.amazonaws.com
            Action: sts:AssumeRole
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
      Policies:
        - PolicyName: S3ReadPolicy
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Effect: Allow
                Action:
                  - s3:GetObject
                Resource: !Sub "arn:aws:s3:::mi-bucket-procesamiento-${AWS::AccountId}/*"

  MiBucket:
    Type: AWS::S3::Bucket
    Properties:
      BucketName: !Sub "mi-bucket-procesamiento-${AWS::AccountId}"
      NotificationConfiguration:
        LambdaConfigurations:
          - Event: s3:ObjectCreated:*
            Function: !GetAtt MiLambdaProcesarS3.Arn

  AllowS3ToInvokeLambda:
    Type: AWS::Lambda::Permission
    Properties:
      FunctionName: !Ref MiLambdaProcesarS3
      Action: lambda:InvokeFunction
      Principal: s3.amazonaws.com
      SourceArn: !Sub "arn:aws:s3:::mi-bucket-procesamiento-${AWS::AccountId}"   # ← ARN construido manualmente

  # ==================== FUNCIÓN LAMBDA ====================
  MiLambdaProcesarS3:
    Type: AWS::Lambda::Function
    Properties:
      FunctionName: ProcesarArchivoS3-Python
      Runtime: python3.12
      Role: !GetAtt LambdaExecutionRole.Arn
      Handler: index.lambda_handler
      Timeout: 30
      Code:
        ZipFile: |
          import json
          import boto3
          import urllib.parse

          s3 = boto3.client('s3')

          def lambda_handler(event, context):
              print("Evento recibido:", json.dumps(event, indent=2))
              
              # Obtener información del archivo subido
              bucket = event['Records'][0]['s3']['bucket']['name']
              key = urllib.parse.unquote_plus(event['Records'][0]['s3']['object']['key'])
              
              print(f"Archivo subido: s3://{bucket}/{key}")
              
              # Aquí puedes procesar el archivo (ejemplo: leer metadata)
              response = s3.get_object(Bucket=bucket, Key=key)
              content_type = response['ContentType']
              
              print(f"Tipo de contenido: {content_type}")
              
              return {
                  'statusCode': 200,
                  'body': f"Procesado correctamente el archivo {key} de tipo {content_type}"
              }


Outputs:
  LambdaFunctionNamePython:
    Value: !Ref MiLambdaProcesarS3

  BucketName:
    Value: !Ref MiBucket  