# General variables
variable "environment" {
  description = "Name of the environment, e.g. dev, qa, prod"
  type        = string
}

variable "service_name" {
  description = "Service name, without environment prefix"
  type        = string
}

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 "aws_region" {
  description = "Name of the AWS region"
  type        = string
  default     = "us-east-1"
}

variable "fully_qualified_domain_name" {
  description = "Fully qualified domain name for the SPA (also used for S3 bucket name)"
  type        = string
  default     = null
}

variable "vpc_id" {
  description = "VPC ID in which to create resources"
  type        = string
}

variable "load_balancer_subnet_ids" {
  description = "Subnet IDs for the application load balancer"
  type        = list(string)
}

variable "vpc_endpoint_name" {
  description = "Name tag of the S3 interface VPC endpoint to look up. This should be provided when there is more than one S3 Interface endpoint."
  type        = string
  default     = ""
}

# Security group variables
variable "allow_vpc_private_subnets" {
  description = "Whether to automatically allow traffic from VPC private subnets via managed prefix lists"
  type        = bool
  default     = false
}
variable "ingress_cidr_blocks" {
  description = "CIDR blocks from which to allow traffic"
  type        = list(string)
  default     = []
}

variable "ingress_prefix_list_names" {
  description = "Names of managed prefix lists from which to allow traffic"
  type        = list(string)
  default     = []
}

# Application Load Balancer variables
variable "load_balancer_is_internal" {
  description = "Whether the load balancer is internal"
  type        = bool
  default     = true
}

variable "load_balancer_idle_timeout" {
  description = "Load balancer idle timeout in seconds"
  type        = number
  default     = 60
}

variable "load_balancer_enable_deletion_protection" {
  description = "Whether to enable deletion protection on the load balancer"
  type        = bool
  default     = false
}

variable "load_balancer_access_custom_logs_bucket" {
  description = "Custom S3 bucket for storing load balancer access logs. Only set if the bucket cannot log to the default shared bucket"
  type        = string
  default     = ""
}

variable "load_balancer_access_custom_logs_prefix" {
  description = "Custom prefix for load balancer access logs in S3 bucket"
  type        = string
  default     = ""
}

variable "load_balancer_listener_port" {
  description = "Port for HTTPS listener"
  type        = number
  default     = 443
}

variable "load_balancer_ssl_policy" {
  description = "SSL policy for HTTPS listener"
  type        = string
  default     = "ELBSecurityPolicy-TLS13-1-2-2021-06"
}

# Target group health check variables
variable "health_check_interval" {
  description = "Interval between health checks"
  type        = number
  default     = 10
}

variable "health_check_timeout" {
  description = "Timeout for health checks"
  type        = number
  default     = 5
}

variable "health_check_healthy_threshold" {
  description = "Number of consecutive successful health checks before considering target healthy"
  type        = number
  default     = 3
}

variable "health_check_unhealthy_threshold" {
  description = "Number of consecutive failed health checks before considering target unhealthy"
  type        = number
  default     = 3
}

variable "health_check_path" {
  description = "Path for health checks"
  type        = string
  default     = "/"
}

variable "health_check_matcher" {
  description = "HTTP status codes for successful health checks"
  type        = string
  default     = "200"
}

variable "certificate_domain" {
  description = "Domain pattern for ACM certificate lookup (e.g., '*.example.com'). Required."
  type        = string
}

variable "route53_record_enabled" {
  description = "Whether to create a Route53 DNS record"
  type        = bool
  default     = false
}

variable "route53_zone_name" {
  description = "Route53 zone name for DNS record creation"
  type        = string
  default     = null

  validation {
    condition     = var.route53_zone_name != null || !var.route53_record_enabled
    error_message = "route53_zone_name must be set when route53_record_enabled is true"
  }
}

variable "route53_is_private_zone" {
  description = "Whether the Route53 hosted zone is private"
  type        = bool
  default     = false
}

# Listener rule variables
variable "custom_static_path_patterns" {
  description = "Custom path patterns for static assets that should be forwarded directly to S3 (e.g., ['/assets/*', '/index.html'])"
  type        = list(string)
  default     = []
}

variable "static_paths_rule_priority" {
  description = "Priority for the static paths listener rule"
  type        = number
  default     = 100
}

variable "spa_rewrite_rule_priority" {
  description = "Priority for the SPA URL rewrite listener rule"
  type        = number
  default     = 200
}

variable "spa_rewrite_regex" {
  description = "Regex pattern for URL rewriting"
  type        = string
  default     = "^/.*$"
}

variable "spa_rewrite_target" {
  description = "Target object name for URL rewriting, e.g. index.html or index-sme.html"
  type        = string
  default     = "index.html"

  validation {
    condition     = !startswith(var.spa_rewrite_target, "/")
    error_message = "spa_rewrite_target is an object and must not start with a leading slash"
  }
}

variable "spa_rewrite_path_patterns" {
  description = "Path patterns to apply URL rewriting to"
  type        = list(string)
  default     = ["/*"]
}

variable "custom_waf_name" {
  description = "Name of custom WAF to associate with the load balancer"
  type        = string
  default     = ""
}

# S3 bucket variables (pass-through to terraform-s3 module)
variable "s3_bucket_policy_overrides" {
  description = "List of additional IAM policy document JSONs to merge with bucket policy"
  type        = list(string)
  default     = null
}

variable "s3_apply_replication_configuration" {
  description = "List of maps containing replication configuration"
  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)
    replica_kms_key_arn               = optional(string)
    source_kms_key_arns               = optional(list(string), [])
  }))
  default = []
}

variable "s3_apply_replication_destination_configuration" {
  description = "List of maps containing replication destination configuration"
  type = list(object({
    replication_source_iam_role_arn = string
    grant_kms_access                = optional(bool, false)
  }))
  default = []
}

variable "s3_custom_logging_bucket" {
  type        = string
  description = "Custom logging bucket for S3 access logs; should only be set if the bucket cannot log to the default shared bucket"
  default     = null
}

variable "s3_custom_logging_prefix" {
  type        = string
  description = "Custom prefix for S3 access log files; should only be set if the bucket cannot log to the default shared bucket"
  default     = null
}

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

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

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

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

variable "s3_lifecycle_rules_abort_incomplete_multipart_upload_days" {
  type    = list(any)
  default = []
}

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

variable "s3_read_only_policy" {
  description = "Whether to create a read-only IAM policy for the bucket"
  type        = bool
  default     = false
}

variable "s3_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 "deploy_role_arn" {
  type        = string
  description = "IAM role ARN allowed to deploy to the S3 bucket (read and write object operations)"
  default     = "arn:aws:iam::437795906767:role/prod-cdn-deploy-role"
}

variable "enable_pull_request_instances" {
  type        = bool
  description = "Enable CORS headers for pull request instance support. Cannot be enabled in prod environments."
  default     = false

  validation {
    condition     = var.enable_pull_request_instances == false || (var.environment != "prod")
    error_message = "enable_pull_request_instances cannot be set to true when environment is 'prod'"
  }
}

# Locals
locals {
  combined_resource_tags = merge(
    {
      environment        = var.environment
      service_name       = var.service_name
      application_family = var.application_family
      terraformed        = true
    },
    var.additional_tags
  )
  
  load_balancer_access_logs_s3_bucket_name = var.load_balancer_access_custom_logs_bucket != "" ? var.load_balancer_access_custom_logs_bucket : "shared-orcd-lb-logs"
  load_balancer_access_logs_prefix = var.load_balancer_access_custom_logs_prefix != "" ? var.load_balancer_access_custom_logs_prefix : "${var.environment}-${var.service_name}"
  # Frontend build and deployment processes upload all objects to the object prefix frontend-{service_name}/*, so we need to rewrite to that path for the SPA to adhere to this pattern
  spa_rewrite_target = "/frontend-${var.service_name}/${var.spa_rewrite_target}"
  path_patterns_for_static_assets = length(var.custom_static_path_patterns) > 0 ? var.custom_static_path_patterns : ["/frontend-${var.service_name}/frontend-${var.service_name}-*", "/frontend-${var.service_name}/prs/*", "/frontend-${var.service_name}/assets/*", "${local.spa_rewrite_target}"]
  waf_name = var.custom_waf_name != "" ? var.custom_waf_name : "${var.environment}-orcd-waf-block"
}
