# AWS Batch Infrastructure for {{ project_name }}
# Generated by Prism — do not edit directly.
#
# Apply with:
#   cd deploy/aws-batch
#   terraform init
#   terraform plan
#   terraform apply

terraform {
  required_version = ">= 1.5"

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
}

provider "aws" {
  region = "{{ region }}"

  default_tags {
    tags = {
      Project   = "{{ project_name }}"
      ManagedBy = "prisme"
    }
  }
}

# ---------- IAM ----------

resource "aws_iam_role" "batch_execution" {
  name = "{{ project_name_snake }}_batch_execution"

  assume_role_policy = jsonencode({
    Version = "2012-10-17"
    Statement = [
      {
        Action = "sts:AssumeRole"
        Effect = "Allow"
        Principal = {
          Service = "ecs-tasks.amazonaws.com"
        }
      }
    ]
  })
}

resource "aws_iam_role_policy_attachment" "batch_execution_policy" {
  role       = aws_iam_role.batch_execution.name
  policy_arn = "arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy"
}

resource "aws_iam_role" "batch_job" {
  name = "{{ project_name_snake }}_batch_job"

  assume_role_policy = jsonencode({
    Version = "2012-10-17"
    Statement = [
      {
        Action = "sts:AssumeRole"
        Effect = "Allow"
        Principal = {
          Service = "ecs-tasks.amazonaws.com"
        }
      }
    ]
  })
}

# ---------- Compute Environment ----------

resource "aws_batch_compute_environment" "main" {
  compute_environment_name = "{{ compute_environment_name }}"
  type                     = "MANAGED"
  state                    = "ENABLED"

  compute_resources {
    type      = "FARGATE"
    max_vcpus = {{ max_vcpus }}

    {% if subnets %}
    subnets = [
      {% for subnet in subnets %}
      "{{ subnet }}",
      {% endfor %}
    ]
    {% else %}
    subnets = data.aws_subnets.default.ids
    {% endif %}

    {% if security_groups %}
    security_group_ids = [
      {% for sg in security_groups %}
      "{{ sg }}",
      {% endfor %}
    ]
    {% else %}
    security_group_ids = [data.aws_security_group.default.id]
    {% endif %}
  }
}

{% if not subnets %}
data "aws_vpc" "default" {
  default = true
}

data "aws_subnets" "default" {
  filter {
    name   = "vpc-id"
    values = [data.aws_vpc.default.id]
  }
}
{% endif %}

{% if not security_groups %}
data "aws_security_group" "default" {
  vpc_id = data.aws_vpc.default.id
  name   = "default"
}
{% endif %}

# ---------- Job Queue ----------

resource "aws_batch_job_queue" "main" {
  name     = "{{ job_queue_name }}"
  state    = "ENABLED"
  priority = 1

  compute_environment_order {
    order               = 1
    compute_environment = aws_batch_compute_environment.main.arn
  }
}

# ---------- Job Definitions ----------

{% for job in jobs %}
resource "aws_batch_job_definition" "{{ job.name | replace("-", "_") }}" {
  name = "{{ project_name }}-{{ job.name }}"
  type = "container"
  platform_capabilities = ["{{ job.platform }}"]

  container_properties = jsonencode({
    image   = "{{ job.docker_image or (docker_registry + '/' + project_name + '-backend:latest') }}"
    command = {{ job.command | tojson }}

    resourceRequirements = [
      { type = "VCPU", value = "{{ job.vcpus }}" },
      { type = "MEMORY", value = "{{ job.memory_mb }}" },
    ]

    executionRoleArn = aws_iam_role.batch_execution.arn
    jobRoleArn       = aws_iam_role.batch_job.arn

    {% if job.environment %}
    environment = [
      {% for key, value in job.environment.items() %}
      { name = "{{ key }}", value = "{{ value }}" },
      {% endfor %}
    ]
    {% endif %}

    networkConfiguration = {
      assignPublicIp = "ENABLED"
    }
  })

  retry_strategy {
    attempts = {{ job.retry_attempts }}
  }

  timeout {
    attempt_duration_seconds = {{ job.timeout_seconds }}
  }

  tags = {
    Job = "{{ job.name }}"
  }
}

{% if job.schedule %}
# EventBridge rule for scheduled execution
resource "aws_cloudwatch_event_rule" "{{ job.name | replace("-", "_") }}" {
  name                = "{{ project_name }}-{{ job.name }}-schedule"
  schedule_expression = "{{ job.schedule }}"
  state               = "ENABLED"
}

resource "aws_cloudwatch_event_target" "{{ job.name | replace("-", "_") }}" {
  rule     = aws_cloudwatch_event_rule.{{ job.name | replace("-", "_") }}.name
  arn      = aws_batch_job_queue.main.arn
  role_arn = aws_iam_role.batch_events.arn

  batch_target {
    job_definition = aws_batch_job_definition.{{ job.name | replace("-", "_") }}.arn
    job_name       = "{{ project_name }}-{{ job.name }}-scheduled"
  }
}
{% endif %}
{% endfor %}

{% if jobs | selectattr("schedule") | list %}
# EventBridge → Batch IAM role (for scheduled jobs)
resource "aws_iam_role" "batch_events" {
  name = "{{ project_name_snake }}_batch_events"

  assume_role_policy = jsonencode({
    Version = "2012-10-17"
    Statement = [
      {
        Action = "sts:AssumeRole"
        Effect = "Allow"
        Principal = {
          Service = "events.amazonaws.com"
        }
      }
    ]
  })
}

resource "aws_iam_role_policy" "batch_events_submit" {
  name = "batch-submit-job"
  role = aws_iam_role.batch_events.id

  policy = jsonencode({
    Version = "2012-10-17"
    Statement = [
      {
        Effect   = "Allow"
        Action   = "batch:SubmitJob"
        Resource = "*"
      }
    ]
  })
}
{% endif %}

# ---------- Outputs ----------

output "compute_environment_arn" {
  value = aws_batch_compute_environment.main.arn
}

output "job_queue_arn" {
  value = aws_batch_job_queue.main.arn
}

{% for job in jobs %}
output "{{ job.name | replace("-", "_") }}_job_definition_arn" {
  value = aws_batch_job_definition.{{ job.name | replace("-", "_") }}.arn
}
{% endfor %}
