data "aws_caller_identity" "current" {}

data "aws_sqs_queue" "source_queue" {
  name = "${var.environment}-${var.sqs_queue_name}-queue"
}

data "aws_sfn_state_machine" "existing_sfn" {
  name = "${var.environment}-sfn-finalize-bulk-session"
}

data "aws_iam_policy_document" "eventbridge_pipe_assume_role_policy" {
  statement {
    effect = "Allow"
    actions = ["sts:AssumeRole"]

    principals {
      type        = "Service"
      identifiers = ["pipes.amazonaws.com"]
    }

    condition {
      test     = "StringEquals"
      variable = "aws:SourceAccount"
      values   = [data.aws_caller_identity.current.account_id]
    }
  }
}

resource "aws_iam_role" "eventbridge_pipe_role" {
  assume_role_policy = data.aws_iam_policy_document.eventbridge_pipe_assume_role_policy.json
}

data "aws_iam_policy_document" "eventbridge_pipe_sqs_source_policy" {
  statement {
    effect = "Allow"
    actions = [
      "sqs:DeleteMessage",
      "sqs:GetQueueAttributes",
      "sqs:ReceiveMessage",
    ]
    resources = [
      data.aws_sqs_queue.source_queue.arn
    ]
  }
}

resource "aws_iam_role_policy" "eventbridge_pipe_sqs_source_policy" {
  role   = aws_iam_role.eventbridge_pipe_role.id
  policy = data.aws_iam_policy_document.eventbridge_pipe_sqs_source_policy.json
}

data "aws_iam_policy_document" "eventbridge_pipe_sfn_target_policy" {
  statement {
    effect = "Allow"
    actions = [
      "states:StartExecution",
    ]
    resources = [
      data.aws_sfn_state_machine.existing_sfn.arn
    ]
  }
}

resource "aws_iam_role_policy" "eventbridge_pipe_sfn_target_policy" {
  role   = aws_iam_role.eventbridge_pipe_role.id
  policy = data.aws_iam_policy_document.eventbridge_pipe_sfn_target_policy.json
}

resource "aws_pipes_pipe" "eventbridge_pipe" {
  name       = "${var.environment}-${var.service_name}-${var.sqs_queue_name}-pipe"
  role_arn   = aws_iam_role.eventbridge_pipe_role.arn
  source     = data.aws_sqs_queue.source_queue.arn
  target     = data.aws_sfn_state_machine.existing_sfn.arn

  source_parameters {
    sqs_queue_parameters {
      batch_size                         = 1
      maximum_batching_window_in_seconds = 5
    }
  }

  target_parameters {
    step_function_state_machine_parameters {
      invocation_type = "FIRE_AND_FORGET"
    }
    input_template = <<EOF
{
  "assets_required": <$.body.assets_required>,
  "bucket": <$.body.bucket>,
  "bulk_session_id": <$.body.bulk_session_id>,
  "bulk_session_ingestion_id": <$.body.bulk_session_ingestion_id>,
  "correlation_id": <$.body.correlation_id>,
  "execution_arn": <$.body.execution_arn>,
  "identity_uuid": <$.body.identity_uuid>,
  "ingestion_status": <$.body.ingestion_status>,
  "key": <$.body.key>,
  "send_notifications": <$.body.send_notifications>,
  "submit_products": <$.body.submit_products>
}
EOF
  }
}
