# Own ALB/web-traffic security group, same shape as myzrok/terraform/security-groups.tf's
# zrok_billing_web_traffic (443 + 80 open, since myzrok-orchestration gets its own ALB rather than
# sharing zrok-billing's).
resource "aws_security_group" "myzrok_orchestration_web_traffic" {
  name        = "myzrok-orchestration-web-traffic-${local.environment}"
  description = "Web traffic ingress and egress rules for myzrok-orchestration"
  vpc_id      = data.terraform_remote_state.zrok-core.outputs.vpc_id

  ingress {
    from_port   = 443
    to_port     = 443
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  ingress {
    from_port   = 80
    to_port     = 80
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }

  tags = merge(local.cost_tags, {
    Name = "myzrok-orchestration-web-traffic-${local.environment}"
  })
}

# ALB <-> task traffic on the container port itself, same self-referencing pattern as
# myzrok/terraform/zrok-billing.tf's zrok_billing security group (the ALB and the ECS task both
# carry this SG, so the self rule is what actually permits the ALB to reach the task).
resource "aws_security_group" "myzrok_orchestration" {
  name        = "myzrok-orchestration-${local.environment}"
  description = "Allow access to myzrok-orchestration"
  vpc_id      = data.terraform_remote_state.zrok-core.outputs.vpc_id

  ingress {
    from_port = local.container_port
    to_port   = local.container_port
    protocol  = "tcp"
    self      = true
  }

  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }

  tags = merge(local.cost_tags, {
    Name = "myzrok-orchestration-${local.environment}"
  })
}

# The existing zrok Postgres DB's security group (myzrok/terraform/security-groups.tf's
# zrok_billing_db_sg equivalent) - needed so this task's egress to postgres.zrok.<env> is actually
# permitted on the DB side, same as zrok-billing's task already is.
data "aws_security_group" "zrok_db_sg" {
  name = "zrok-postgres-${local.environment}"
}

resource "aws_security_group" "myzrok_orchestration_db_sg" {
  name        = "myzrok-orchestration-mysql-${local.environment}"
  description = "myzrok-orchestration MySQL ${local.environment}"
  vpc_id      = data.terraform_remote_state.zrok-core.outputs.vpc_id

  ingress {
    from_port = 3306
    to_port   = 3306
    protocol  = "tcp"
    self      = true
  }

  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }

  tags = merge(local.cost_tags, {
    Name = "myzrok-orchestration-mysql-${local.environment}"
  })
}
