provider "aws" {
  region = "us-east-1"
}

provider "snowflake" {
  account_name = var.account_name
  preview_features_enabled = [
    "snowflake_storage_integration_resource",
    "snowflake_stage_resource",
  ]
}

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

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

  env                 = var.environment
  bucket_name         = var.service_name
  application_family  = "accounting"
  s3_read_only_policy = true

  apply_server_side_encryption_by_default = {
    sse_algorithm = "AES256"
  }

  lifecycle_rules_options_current_version_expiration = [
    {
      prefix  = ""
      enabled = true
      days    = 7
    }
  ]

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

  lifecycle_rules_abort_incomplete_multipart_upload_days = [
    {
      prefix  = ""
      enabled = true
      days    = 1
    }
  ]
}

module "s3_read_write_policy" {
  source = "git@github.com:theorchard/terraform-iam-policy-templates.git//documents/s3/buckets_with_prefixes?ref=0.4.0"

  buckets = [
    { bucket = module.temp_statementdb_s3_bucket.s3_bucket_name_output },
  ]
  action_types = ["read", "write"]
}

resource "aws_iam_policy" "s3_read_write_policy" {
  name   = "S3-${var.environment}-${var.service_name}-RW"
  policy = module.s3_read_write_policy.policy.json
}

resource "aws_iam_user_policy_attachment" "read_write_policy_attachment" {
  user       = "jkass"
  policy_arn = aws_iam_policy.s3_read_write_policy.arn
}

data "aws_iam_policy_document" "storage_integration_iam_role_assume_role_policy_document" {
  statement {
    actions = ["sts:AssumeRole"]

    principals {
      type = "AWS"
      identifiers = [
        "arn:aws:iam::494544507972:user/c_orchard_stage_volume",
      ]
    }
    condition {
      test     = "StringEquals"
      values   = ["ORCHARD_SFCRole=881_9KvGw2AtYcyM8Kf2oicVxr+fU+o="]
      variable = "sts:ExternalId"
    }
  }
}

# Storage integration role
resource "aws_iam_role" "storage_integration_iam_role" {
  name               = "${var.service_name}-storage-integration-role"
  assume_role_policy = data.aws_iam_policy_document.storage_integration_iam_role_assume_role_policy_document.json
}

resource "aws_iam_role_policy_attachment" "read_only_policy_attachment" {
  role       = aws_iam_role.storage_integration_iam_role.name
  policy_arn = module.temp_statementdb_s3_bucket.s3_read_only_policy_arn_output
}
