resource "aws_s3_bucket" "bucket" {
  bucket = var.bucketname
  acl    = "private"

  cors_rule {
    allowed_headers = ["Content-Type", "Authorization"]
    allowed_methods = ["PUT"]
    allowed_origins = var.allowed_origins
    expose_headers = ["ETag"]
    max_age_seconds = 3000
  }

  server_side_encryption_configuration {
    rule {
      apply_server_side_encryption_by_default {
        sse_algorithm = "AES256"
      }
    }
  }

  lifecycle {
    prevent_destroy = true
  }
}

resource "aws_iam_user" "presign_frontend_user" {
  name = "presign_frontend_user-${var.bucketname}"
  path = "/system/"
}

resource "aws_iam_access_key" "presign_frontend_user_access_key" {
  user = aws_iam_user.presign_frontend_user.name
}

resource "aws_secretsmanager_secret" "presign_frontend_user_access_key" {
  name = "${var.bucketname}/presign_frontend/access_key"
}

resource "aws_secretsmanager_secret_version" "presign_frontend_user_access_key" {
  secret_id     = aws_secretsmanager_secret.presign_frontend_user_access_key.id
  secret_string = aws_iam_access_key.presign_frontend_user_access_key.id
}

resource "aws_secretsmanager_secret" "presign_frontend_user_secret_key" {
  name = "${var.bucketname}/presign_frontend/secret_key"
}

resource "aws_secretsmanager_secret_version" "presign_frontend_user_secret_key" {
  secret_id     = aws_secretsmanager_secret.presign_frontend_user_secret_key.id
  secret_string = aws_iam_access_key.presign_frontend_user_access_key.secret
}

resource "aws_iam_user_policy" "presign_frontend_user_policy" {
  name = "presign_frontend_user_policy-${var.bucketname}"
  user = aws_iam_user.presign_frontend_user.name

  policy = <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "s3:PutObject",
        "s3:PutObjectAcl",
        "s3:GetObject",
        "s3:GetObjectAcl",
        "s3:DeleteObject"
      ],
      "Resource": "arn:aws:s3:::${aws_s3_bucket.bucket.bucket}/*"
    }
  ]
}
EOF
}

resource "aws_s3_bucket_versioning" "versioning" {
  count  = var.enable_versioning ? 1 : 0
  bucket = aws_s3_bucket.bucket.id
  versioning_configuration {
    status = "Enabled"
  }
}

resource "aws_s3_bucket_public_access_block" "block_public" {
  bucket                  = aws_s3_bucket.bucket.id
  block_public_acls       = true
  block_public_policy     = true
  ignore_public_acls      = true
  restrict_public_buckets = true
}