variable "env" {
  description = "prod, qa or dev"
  default     = "dev"
}

variable "bucket_name" {
  description = "Name of the S3 bucket"
}

variable "kms_key_enabled" {
  description = "When enabled, this will create a KMS key and set it as the default encryption key for the bucket. Using KMS is more recommended than AES256, but all the services, that interact with objects in the bucket must get permissions to use the key."
  type        = bool
  default     = false
}

variable "kms_key_name" {
  description = "Alias for the KMS Key"
  default     = ""
}

variable "kms_key_required" {
  description = "When enabled together with the 'kms_key_enabled' flag, this adds a bucket policy that blocks any object uploads without the required KMS key ID specified. Use with caution as it will block uploads that rely on the default bucket encryption settings."
  type        = bool
  default     = false
}

variable "kms_key_policy_overrides" {
  description = "List of IAM policy document JSONs to merge with the KMS key policy, if KMS key is enabled. Statements with the same SID will be overridden."
  type        = list(string)
  default     = []
}

variable "block_public_access" {
  type        = bool
  description = "Whether or not to block public access"
  default     = true
}

variable "apply_server_side_encryption_by_default" {
  description = "Map containing server-side encryption configuration."
  type        = map(string)

  validation {
    condition     = length(var.apply_server_side_encryption_by_default) > 0
    error_message = "KMS or AES256 encryption required."
  }
}

variable "apply_replication_configuration" {
  description = "List of maps containing replication configuration as a source bucket."
  type = list(object({
    priority                          = optional(number, 0)
    prefix                            = string
    enabled                           = bool
    delete_marker_replication_enabled = bool
    destination_bucket                = string
    storage_class                     = string
    metrics_enabled                   = optional(bool, true)
    replication_time_control_enabled  = optional(bool, false)
    replicate_kms_encrypted_objects   = optional(bool, false)      # Not required for buckets that only use AWS managed keys
    replica_kms_key_arn               = optional(string)           # Required if replicate_kms_encrypted_objects is true
    source_kms_key_arns               = optional(list(string), []) # If replicating KMS-encrypted objects, specify any additional KMS key ARNs that objects are encrypted with. If the bucket is configured to use KMS for default encryption, that key is included automatically.
  }))
  default = []
  validation {
    condition = alltrue([
      for rule in var.apply_replication_configuration : !rule.replication_time_control_enabled || rule.metrics_enabled
    ])
    error_message = "Metrics must be enabled if replication time control is enabled"
  }
  validation {
    condition = alltrue([
      for rule in var.apply_replication_configuration : !rule.replicate_kms_encrypted_objects || rule.replica_kms_key_arn != null
    ])
    error_message = "Replica KMS key ID must be specified if replication of KMS-encrypted objects is enabled"
  }
}

variable "apply_replication_destination_configuration" {
  description = "List of maps containing replication configuration as a destination bucket."
  type = list(object({
    replication_source_iam_role_arn = string
    grant_kms_access                = optional(bool, false) # Grants the replication role access to the KMS key via the KMS key policy. Only required when performing cross-account replication of KMS-encrypted objects.
  }))
  default = []
}

variable "bucket_key_enabled" {
  description = "Whether to enable bucket key for CMK encrypted buckets"
  type        = bool
  default     = false
}

variable "custom_logging_bucket" {
  type        = string
  description = "Custom logging bucket. Overrides programmatically derived name."
  default     = ""
}

variable "custom_logging_prefix" {
  type        = string
  description = "Custom prefix for log files in logging bucket. Overrides hardcoded value."
  default     = ""
}

variable "lifecycle_rules_options_noncurrent_version_transition" {
  type = list(object({
    prefix        = string
    enabled       = bool
    days          = number
    storage_class = string
  }))
  default = [
  ]
}

variable "lifecycle_rules_options_current_version_transition" {
  type = list(object({
    prefix        = string
    enabled       = bool
    days          = number
    storage_class = string
  }))
  default = [
  ]
}

variable "lifecycle_rules_options_noncurrent_version_expiration" {
  type = list(object({
    prefix  = string
    enabled = bool
    days    = number
  }))
  default = [
  ]
}

variable "lifecycle_rules_options_current_version_expiration" {
  type = list(object({
    prefix  = string
    enabled = bool
    days    = number
  }))
  default = [
  ]
}

variable "lifecycle_rules_abort_incomplete_multipart_upload_days" {
  type = list(any)
  default = [{
    prefix  = ""
    enabled = true
    days    = 7
  }]
}

variable "lifecycle_rules_expired_object_delete_markers_expiration" {
  type = list(object({
    prefix  = string
    enabled = bool
  }))
  default = []
}

variable "custom_object_ownership" {
  description = "Overrides bucket object ownership. Should be 'BucketOwnerPreferred' or 'ObjectWriter'."
  type        = string
  default     = ""
}

variable "acl_policy_grants" {
  description = "List of maps containing ACL policies."
  type = list(object({
    id         = string
    type       = string
    permission = string
  }))
  default = []
}

# IAM policy settings
variable "s3_read_only_policy" {
  default = false
}

variable "s3_custom_read_only_policy_name" {
  description = "Custom read only policy name"
  type        = string
  default     = ""
}

# Bucket settings
variable "custom_bucket_name" {
  description = "Override bucket name"
  default     = ""
}

variable "bucket_cors_rule" {
  type = list(object({
    allowed_headers = list(string)
    allowed_methods = list(string)
    allowed_origins = list(string)
    expose_headers  = list(string)
    max_age_seconds = number
    }
  ))
  description = "List of CORS rules for s3 bucket"
  default     = []
}

variable "acceleration_status" {
  description = "Sets the accelerate configuration of an existing bucket. Can be Enabled or Suspended."
  default     = "Suspended"
}

variable "bucket_policy_overrides" {
  description = "List of IAM policy document JSONs to merge with bucket policy. Statements with the same SID will be overridden."
  type        = list(string)
  default     = []
}

variable "application_family" {
  type        = string
  description = "Application family to which this service belongs"
}

variable "additional_tags" {
  type        = map(string)
  description = "Optional map of additional tags to set on resources. These will be combined with programmatically set required tags."
  default     = {}
}

variable "access_logging_enabled" {
  type        = bool
  description = "Whether or not access logging should be enabled. This should only ever be disabled to prevent a bucket logging to itself."
  default     = true
}

variable "storage_lens_configuration" {
  type = object({
    enabled                                    = bool
    activity_metrics_enabled                   = optional(bool, true)
    advanced_cost_optimization_metrics_enabled = optional(bool, false)
    advanced_data_protection_metrics_enabled   = optional(bool, false)
    cloudwatch_metrics_export_enabled          = optional(bool, true)
    detailed_status_code_metrics_enabled       = optional(bool, true)
    prefix_level_storage_metrics_enabled       = optional(bool, true)
    prefix_level_max_depth                     = optional(number, 5)
    prefix_level_min_storage_bytes_percentage  = optional(number, 3)
  })
  description = "Map containing storage lens configuration."
  default = {
    enabled = false
  }
}

variable "replication_helper_allowed" {
  description = "Allows backup account objects larger than 5gb to be replicated to this bucket via helper lambda"
  type        = bool
  default     = false
}

variable "replication_helper_arn" {
  description = "ARN of the backup account root"
  type        = string
  default     = "arn:aws:iam::079637511089:root"
}

variable "default_inventory_enabled" {
  description = "Whether default inventory is to be enabled. Should be disabled only when there is a problem with creating this or other special case."
  default     = true
  type        = bool
}

variable "additional_inventory_configurations" {
  description = "Additional inventory configurations."
  type = map(object({
    destination_bucket_arn   = string
    destination_prefix       = string
    filter_prefix            = string
    format                   = string
    frequency                = string
    included_object_versions = string
    optional_fields          = set(string)
  }))
  default = {}

  validation {
    condition = alltrue([
      for k, v in var.additional_inventory_configurations :
      contains(["csv", "ORC", "Parquet"], v.format)
    ])
    error_message = "Format must be one of: 'csv', 'ORC', or 'Parquet'."
  }

  validation {
    condition = alltrue([
      for k, v in var.additional_inventory_configurations :
      contains(["Daily", "Weekly"], v.frequency)
    ])
    error_message = "Frequency must be either 'Daily' or 'Weekly'."
  }

  validation {
    condition = alltrue([
      for k, v in var.additional_inventory_configurations :
      contains(["All", "Current"], v.included_object_versions)
    ])
    error_message = "Included object versions must be either 'All' or 'Current'."
  }

  validation {
    condition = alltrue([
      for k, v in var.additional_inventory_configurations :
      alltrue([
        for field in v.optional_fields :
        contains([
          "Size", "LastModifiedDate", "StorageClass", "ETag", "IsMultipartUploaded",
          "ReplicationStatus", "EncryptionStatus", "ObjectLockRetainUntilDate", "ObjectLockMode",
          "ObjectLockLegalHoldStatus", "IntelligentTieringAccessTier", "BucketKeyStatus", "ChecksumAlgorithm",
          "ObjectAccessControlList", "ObjectOwner"
        ], field)
      ])
    ])
    error_message = "Invalid optional field. Please check the list of allowed optional fields."
  }
}

variable "permissions_boundary_enabled" {
  type        = bool
  description = <<EOF
  Whether or not to set a permissions boundary to limit the permissions of IAM roles created by this module.
  By default, this is true in dev (to allow local Terraform execution) and false in other environments.
EOF
  default     = null
}

variable "permissions_boundary_policy_name" {
  type        = string
  description = "The name of the policy to use as the permissions boundary for the IAM roles created by this module, if permissions_boundary_enabled is true."
  default     = "dev-permissions-boundary-policy"
}


variable "enable_guardduty_malware_protection" {
  description = "Enable GuardDuty malware protection for the bucket."
  type        = bool
  default     = false
}
