terraform {
  required_version = ">= 1.15.0, < 2.0.0"
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = ">= 6.0, < 7.0"
    }
  }
}

provider "aws" {
  region = "ap-south-1"
}

module "sg" {
  source = "../../modules/security-groups"

  vpc_id      = "vpc-0a2e1bc9f29f31215"
  name_prefix = "sandbox-sg-test"

  security_groups = {

    web = {
      name_suffix = "web-sg"
      description = "Web tier - exercises multi-CIDR, IPv6, self"

      ingress_rules = [
        {
          description      = "HTTPS from internet"
          protocol         = "tcp"
          from_port        = 443
          to_port          = 443
          ipv4_cidr_blocks = ["0.0.0.0/0"]
        },
        {
          description      = "SSH from office + VPN"
          protocol         = "tcp"
          from_port        = 22
          to_port          = 22
          ipv4_cidr_blocks = ["10.0.0.0/16", "192.168.50.0/24"]
        },
        {
          description      = "HTTPS from internet (IPv6)"
          protocol         = "tcp"
          from_port        = 443
          to_port          = 443
          ipv6_cidr_blocks = ["::/0"]
        },
        {
          description = "Health check between web instances"
          protocol    = "tcp"
          from_port   = 8080
          to_port     = 8080
          self        = true
        },
      ]

      egress_rules = [
        {
          description   = "To db tier"
          protocol      = "tcp"
          from_port     = 5432
          to_port       = 5432
          source_sg_key = "db"
        },
        {
          description  = "To pre-existing default SG"
          protocol     = "tcp"
          from_port    = 9100
          to_port      = 9100
          source_sg_id = "sg-0a1f705f08895b7f9"
        },
      ]
    }

    db = {
      name_suffix = "db-sg"
      description = "DB tier - exercises source_sg_key"

      ingress_rules = [
        {
          description   = "Postgres from web tier"
          protocol      = "tcp"
          from_port     = 5432
          to_port       = 5432
          source_sg_key = "web"
        },
      ]

      egress_rules = []
    }
  }

  tags = {}
}

output "sg_ids" {
  value = module.sg.ids
}

output "sg_names" {
  value = module.sg.names
}

output "ingress_rule_ids" {
  value = module.sg.ingress_rule_ids
}

output "egress_rule_ids" {
  value = module.sg.egress_rule_ids
}

output "rule_counts" {
  value = module.sg.rule_counts
}
