AWSTemplateFormatVersion: '2010-09-09'
Description: AWS Lambda + DynamoDB

Resources:
  # ==================== ROL IAM ====================
  MiTablaDatos:
    Type: AWS::DynamoDB::Table
    Properties:
      TableName: TablaUsuariosDia14
      AttributeDefinitions:
        - AttributeName: usuarioId
          AttributeType: S
      KeySchema:
        - AttributeName: usuarioId
          KeyType: HASH
      BillingMode: PAY_PER_REQUEST

  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: DynamoDBAccess
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Effect: Allow
                Action:
                  - dynamodb:PutItem
                  - dynamodb:GetItem
                Resource: !GetAtt MiTablaDatos.Arn


  LambdaCRUD:
    Type: AWS::Lambda::Function
    Properties:
      FunctionName: Lambda-Dynamo-Simple
      Runtime: python3.12
      Role: !GetAtt LambdaExecutionRole.Arn
      Handler: index.lambda_handler
      Code:
        ZipFile: |
          import json
          import boto3
          import os

          dynamo = boto3.resource('dynamodb')
          table = dynamo.Table('TablaUsuariosDia14')

          def lambda_handler(event, context):
              method = event['requestContext']['http']['method']
              
              if method == 'POST':
                  # Guardar un dato (enviado en el body)
                  body = json.loads(event.get('body', '{}'))
                  table.put_item(Item={'usuarioId': body['id'], 'nombre': body['nombre']})
                  return {'statusCode': 201, 'body': json.dumps({'mensaje': 'Usuario guardado!'})}
              
              elif method == 'GET':
                  # Leer un dato (vía query string ?id=123)
                  user_id = event.get('queryStringParameters', {}).get('id')
                  if not user_id: return {'statusCode': 400, 'body': 'Falta el id'}
                  
                  response = table.get_item(Key={'usuarioId': user_id})
                  return {'statusCode': 200, 'body': json.dumps(response.get('Item', 'No encontrado'))}

  MiAPI:
    Type: AWS::ApiGatewayV2::Api
    Properties:
      Name: APIDynamoDB
      ProtocolType: HTTP
      Target: !GetAtt LambdaCRUD.Arn

  MiStage:
    Type: AWS::ApiGatewayV2::Stage
    Properties:
      ApiId: !Ref MiAPI
      StageName: prod
      AutoDeploy: true

  AllowAPIGatewayToInvoke:
    Type: AWS::Lambda::Permission
    Properties:
      FunctionName: !Ref LambdaCRUD
      Action: lambda:InvokeFunction
      Principal: apigateway.amazonaws.com
      SourceArn: !Sub "arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${MiAPI}/*"

Outputs:
  LambdaFunctionName:
    Value: !Ref LambdaCRUD