provider "aws" {
  region = var.region
}

terraform {
  backend "s3" {
    bucket  = "prod-songwhip-terraform-state"
    key     = "prod/songwhip-images/terraform.tfstate"
    region  = "us-east-1"
    encrypt = "true"
  }
}

module "songwhip_images" {
  source = "git@github.com:theorchard/terraform-s3.git//modules/s3_bucket?ref=3.0.0"

  env                   = var.environment
  bucket_name           = "songwhip-images"
  custom_logging_bucket = "${var.environment}-songwhip-s3-logs"
  s3_read_only_policy   = false
  application_family    = var.application_family

  lifecycle_rules_options_noncurrent_version_expiration = [
    {
      enabled = true
      prefix  = ""
      days    = 30
    }
  ]

  apply_server_side_encryption_by_default = {
    se_algorithm = "AES256"
  }
}

resource "aws_iam_user" "songwhip_images" {
  name = var.service_name

  tags = {
    terraformed        = true
    Name               = var.service_name
    human              = false
    application_family = var.application_family
    role               = "service-user"
  }
}

data "aws_iam_policy_document" "songwhip_images" {
  statement {
    actions = [
      "s3:GetObject",
      "s3:DeleteObject",
      "s3:ListBucket",
      "s3:PutObject",
    ]

    effect    = "Allow"
    resources = [
      "arn:aws:s3:::${var.environment}-${var.service_name}/*",
      "arn:aws:s3:::${var.environment}-${var.service_name}"
    ]
  }
}

resource "aws_iam_policy" "songwhip_images" {
  name        = "songwhip_images-policy"
  description = "songwhip_images vercel app policy"
  policy      = data.aws_iam_policy_document.songwhip_images.json
}

resource "aws_iam_user_policy_attachment" "songwhip_images" {
  user       = aws_iam_user.songwhip_images.name
  policy_arn = aws_iam_policy.songwhip_images.arn
}

module "secrets_manager" {
  source = "git@github.com:theorchard/terraform-secrets-manager.git//?ref=1.0.4"

  for_each = var.secrets_manager_secret_names

  application_family = var.application_family
  environment        = var.environment
  service_name       = var.service_name
  secret_name        = each.value
}
