locals {
  ami_id = var.ami_id != null ? var.ami_id : data.aws_ami.debian_12.id
  tags = {
    Name         = "${var.environment}-${var.service_name}"
    environment  = var.environment
    service_name = var.service_name
    terraformed  = true
  }
}

data "aws_caller_identity" "current" {}

data "aws_vpc" "current_vpc" {
  id = var.vpc_id
}

data "aws_ami" "debian_12" {
  most_recent = true

  owners = [
    "086679231553",
  ]

  filter {
    name = "virtualization-type"

    values = [
      "hvm",
    ]
  }

  filter {
    name   = "name"
    values = ["debian-12-amd64-*"]
  }

  filter {
    name   = "architecture"
    values = ["x86_64"]
  }
}

resource "aws_launch_template" "launch_template" {
  description             = "${var.environment}-${var.service_name}"
  disable_api_stop        = false
  disable_api_termination = true
  ebs_optimized           = true
  image_id                = local.ami_id
  instance_type           = var.aws_instance_type
  key_name                = var.ssh_keypair_name
  name                    = "${var.environment}-${var.service_name}"
  user_data               = base64encode(var.user_data)
  update_default_version  = true
  vpc_security_group_ids  = [aws_security_group.instance_security_group.id]

  block_device_mappings {
    device_name = data.aws_ami.debian_12.root_device_name
    ebs {
      delete_on_termination = var.root_volume_delete_on_termination
      encrypted             = true
      iops                  = var.root_volume_iops
      throughput            = var.root_volume_throughput
      volume_size           = var.root_volume_size
      volume_type           = var.root_volume_type
    }
  }

  block_device_mappings {
    device_name = var.data_volume_device_name
    ebs {
      delete_on_termination = var.data_volume_delete_on_termination
      encrypted             = true
      iops                  = var.data_volume_iops
      throughput            = var.data_volume_throughput
      volume_size           = var.data_volume_size
      volume_type           = var.data_volume_device_type
    }
  }

  metadata_options {
    http_endpoint = "enabled"
    http_tokens   = "required" # IMDSv2 only
  }

  iam_instance_profile {
    name = aws_iam_instance_profile.iam_instance_profile.name
  }

  monitoring {
    enabled = true
  }

  tag_specifications {
    resource_type = "volume"
    tags          = local.tags
  }

  tags = local.tags

  lifecycle {
    create_before_destroy = true
  }
}

# Auto scaling group
resource "aws_autoscaling_group" "autoscaling_group" {
  name                      = "${var.environment}-${var.service_name}"
  min_size                  = var.min_size
  max_size                  = var.max_size
  desired_capacity          = var.desired_capacity
  default_cooldown          = var.default_cooldown
  health_check_type         = "EC2"
  health_check_grace_period = var.health_check_grace_period
  wait_for_capacity_timeout = var.wait_for_capacity_timeout
  vpc_zone_identifier       = var.vpc_private_subnet_ids

  availability_zone_distribution {
    capacity_distribution_strategy = var.availability_zone_distribution
  }

  launch_template {
    id      = aws_launch_template.launch_template.id
    version = "$Latest"
  }
  enabled_metrics       = var.enabled_metrics
  protect_from_scale_in = var.protect_from_scale_in

  tag {
    key                 = "Name"
    value               = "${var.environment}-${var.service_name}"
    propagate_at_launch = true
  }

  tag {
    key                 = "environment"
    value               = var.environment
    propagate_at_launch = true
  }

  tag {
    key                 = "service_name"
    value               = var.service_name
    propagate_at_launch = true
  }

  lifecycle {
    create_before_destroy = true
  }
}
