provider "aws" {
  region = "us-east-1"

  default_tags {
    tags = module.default_tags.tags
  }
}

terraform {
  backend "s3" {
    bucket  = "shared-orcd-terraform-state"
    key     = "prod/pull-request-review/terraform.tfstate"
    region  = "us-east-1"
    encrypt = "true"
  }
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "5.54.1"
    }
  }
}

data "aws_caller_identity" "current" {}

module "default_tags" {
  source             = "git@github.com:theorchard/terraform-default-tags.git//?ref=1.0.0"
  environment        = var.environment
  application_family = var.application_family
  service_name       = var.service_name
}


data "aws_iam_policy_document" "jenkins_assume_role_policy" {
  version = "2012-10-17"
  statement {
    actions = ["sts:AssumeRole"]
    effect  = "Allow"
    principals {
      type = "AWS"

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

resource "aws_iam_role" "pull_request_review" {
  name = "${var.environment}-${var.service_name}-role"
  assume_role_policy = data.aws_iam_policy_document.jenkins_assume_role_policy.json
}

resource "aws_iam_role_policy" "pull_request_review" {
  name = "${var.environment}-${var.service_name}-policy"
  policy = data.aws_iam_policy_document.pull_request_review.json
  role   = aws_iam_role.pull_request_review.id
}

data "aws_iam_policy_document" "pull_request_review" {
  statement {
    sid    = "AllowBedrockModelInvoke"
    effect = "Allow"

    actions = [
      "bedrock:InvokeModel",
      "bedrock:InvokeModelWithResponseStream",
    ]

    resources = [
      "arn:aws:bedrock:*:*:foundation-model/anthropic*",
      "arn:aws:bedrock:*:*:foundation-model/amazon*",
      "arn:aws:bedrock:*:*:inference-profile/us.anthropic.*"
    ]
  }

  statement {
    sid    = "AllowECRRead"
    effect = "Allow"
    actions = [
      "ecr:BatchCheckLayerAvailability",
      "ecr:BatchGetImage",
      "ecr:DescribeImages",
      "ecr:DescribeRepositories",
      "ecr:GetAuthorizationToken",
      "ecr:GetDownloadUrlForLayer",
      "ecr:ListImages",
      "ecr:ListTagsForResource",
    ]
    resources = ["*"]
  }
}
