# S3 access policy for SME feed file exporter Jenkins job
data "aws_iam_policy_document" "sme_feed_file_exporter_s3_policy_document" {
  # s3:ListBucket without a prefix condition — required for boto3 HeadBucket.
  # s3:prefix is only populated for ListObjects; HeadBucket sends no prefix so
  # a StringLike condition on s3:prefix evaluates false and denies the call.
  statement {
    effect = "Allow"
    actions = [
      "s3:ListBucket",
      "s3:ListBucketMultipartUploads",
    ]
    resources = [
      module.s3_bucket.s3_bucket_arn_output,
    ]
  }

  # Object-level read/write scoped to the settlement files prefix only
  statement {
    effect = "Allow"
    actions = [
      "s3:GetObject*",
      "s3:PutObject*",
      "s3:DeleteObject",
      "s3:AbortMultipartUpload",
      "s3:ListMultipartUploadParts",
    ]
    resources = [
      "${module.s3_bucket.s3_bucket_arn_output}/bw_settlement_files/*",
    ]
  }
}

# Trust: prod Jenkins task agent (437795906767) assumes this role in Accounting prod (989790945997)
data "aws_iam_policy_document" "jenkins_assume_role_policy" {
  statement {
    actions = ["sts:AssumeRole"]

    principals {
      type = "AWS"

      identifiers = [
        "arn:aws:iam::437795906767:role/prod-jenkins-aws-task-agent",
      ]
    }
  }
}

# Named S3 policy for the Jenkins invoke role
resource "aws_iam_policy" "sme_feed_file_exporter_s3_policy" {
  name        = "S3-${var.environment}-${var.bucket_name}-sme-feed-file-exporter-policy"
  description = "Grants Jenkins read/write access to bw_settlement_files prefix on ${var.environment}-${var.bucket_name} for SME feed file exporter (INT-2486)"
  policy      = data.aws_iam_policy_document.sme_feed_file_exporter_s3_policy_document.json

  tags = {
    terraformed        = true
    environment        = var.environment
    application_family = var.application_family
    service_name       = "sme-feed-file-exporter"
  }
}

# Jenkins task agent will assume this role to access S3
resource "aws_iam_role" "jenkins_invoke_role" {
  name               = "${var.environment}-sme-feed-file-exporter-jenkins-role"
  description        = "Assumed by prod Jenkins task agent to upload SAP settlement files to ${var.environment}-${var.bucket_name} S3 bucket (INT-2486)"
  assume_role_policy = data.aws_iam_policy_document.jenkins_assume_role_policy.json

  tags = {
    terraformed        = true
    environment        = var.environment
    application_family = var.application_family
    service_name       = "sme-feed-file-exporter"
  }
}

# Attach S3 policy to Jenkins role
resource "aws_iam_role_policy_attachment" "sme_feed_file_exporter_policy_attachment" {
  role       = aws_iam_role.jenkins_invoke_role.id
  policy_arn = aws_iam_policy.sme_feed_file_exporter_s3_policy.arn
}
