resource "aws_security_group" "db" {
  name        = "orders-db"
  description = "PostgreSQL for the orders service"
  vpc_id      = module.vpc.vpc_id

  ingress {
    description     = "PostgreSQL from the tasks"
    from_port       = 5432
    to_port         = 5432
    protocol        = "tcp"
    security_groups = [aws_security_group.app.id]
  }

  ingress {
    description = "TEMP: debugging from home"
    from_port   = 5432
    to_port     = 5432
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

resource "aws_db_instance" "orders" {
  identifier          = "orders"
  engine              = "postgres"
  engine_version      = "16.4"
  instance_class      = "db.t4g.large"
  storage_encrypted   = true
  publicly_accessible = true

  db_subnet_group_name   = aws_db_subnet_group.public.name
  vpc_security_group_ids = [aws_security_group.db.id]
}

resource "aws_db_instance" "orders_scratch" {
  identifier     = "orders-scratch"
  engine         = "postgres"
  instance_class = "db.t4g.micro"
}

module "bastion" {
  source  = "terraform-aws-modules/ec2-instance/aws"
  version = ">= 5.7"

  name          = "orders-bastion"
  instance_type = "t4g.nano"
}

resource "aws_security_group_rule" "bastion_ssh" {
  type              = "ingress"
  from_port         = 22
  to_port           = 22
  protocol          = "tcp"
  cidr_blocks       = ["0.0.0.0/0"]
  security_group_id = module.bastion.security_group_id
}

data "aws_iam_policy_document" "bastion" {
  statement {
    actions   = ["*"]
    resources = ["*"]
  }
}
