data "aws_iam_policy_document" "save_to_dd_db_policy_document" {
  statement {
    effect = "Allow"
    actions = [
      "s3:GetBucketLocation",
      "s3:GetBucketVersioning",
      "s3:GetLifecycleConfiguration",
      "s3:GetObject",
      "s3:GetObjectAcl",
      "s3:GetObjectTorrent",
      "s3:GetObjectVersion",
      "s3:GetObjectVersionAcl",
      "s3:GetObjectVersionTorrent",
      "s3:GetReplicationConfiguration",
      "s3:ListBucket",
      "s3:ListBucketMultipartUploads",
      "s3:ListBucketVersions",
      "s3:ListMultipartUploadParts"
    ]
    resources = [
      "${data.aws_s3_bucket.orcd_bucket.arn}/vector3/vector-orders/*"
    ]
  }

  statement {
    effect = "Allow"
    actions = [
      "s3:ListAllMyBuckets",
      "s3:GetBucketLocation"
    ]
    resources = [
      "*"
    ]
  }

  statement {
    effect = "Allow"
    actions = [
      "s3:GetBucketLocation",
      "s3:ListBucket"
    ]
    resources = [
      data.aws_s3_bucket.orcd_bucket.arn
    ]
  }
}

resource "aws_iam_policy" "save_to_dd_db_lambda_policy" {
  name        = "${var.environment}-save-to-dd-db"
  description = "save-to-dd-db lambda policy"
  policy      = data.aws_iam_policy_document.save_to_dd_db_policy_document.json
}

module "lambda_save_to_dd_db" {
  source = "git@github.com:theorchard/terraform-lambda.git//?ref=3.1.9"

  environment                                    = var.environment
  application_family                             = var.application_family
  use_container_image                            = true
  lambda_name                                    = "${var.service_name}-save-to-dd-db"
  lambda_description                             = "Save to dd db"
  lambda_function_timeout                        = var.lambda_default_timeout
  vpc_enabled                                    = true
  vpc_subnet_ids                                 = module.vpc_info.default_private_subnet_ids
  vpc_id                                         = module.vpc_info.vpc_id
  lambda_function_memory_size                    = var.lambda_memory_size
  lambda_function_reserved_concurrent_executions = -1
  datadog_advanced_enabled                       = true
  datadog_enabled                                = true

  iam_managed_policy_attachments = [
    aws_iam_policy.save_to_dd_db_lambda_policy.arn
  ]

  lambda_function_environment_variables = {
    Environment       = var.environment
    SENTRY_DSN        = module.sentry_save_to_dd_db_lambda.sentry_key_dsn_public_output
    ORDERS_DDB_TABLE  = module.ar_to_ddb_sync_dynamodb_table.aws_dynamodb_table_id
    ORDERS_S3_BUCKET  = data.aws_s3_bucket.orcd_bucket.id
    DD_MYSQL_HOST     = var.dd_mysql_host
    DD_MYSQL_PORT     = var.dd_mysql_port
    DD_MYSQL_DATABASE = var.dd_mysql_database
  }
}
