# REST API: POST /chat behind the shared Cognito authorizer, streamed from the Lambda.

locals {
  stage_name = "demo"

  cors_headers = {
    "Access-Control-Allow-Origin"  = "'${local.auth.site_origin}'"
    "Access-Control-Allow-Headers" = "'Authorization,Content-Type'"
    "Access-Control-Allow-Methods" = "'POST,OPTIONS'"
  }
}

resource "aws_api_gateway_rest_api" "this" {
  name        = local.name
  description = "Amazon Ergo playground"

  endpoint_configuration {
    types = ["REGIONAL"]
  }
}

resource "aws_api_gateway_authorizer" "cognito" {
  name            = "shared-sign-in"
  rest_api_id     = aws_api_gateway_rest_api.this.id
  type            = "COGNITO_USER_POOLS"
  provider_arns   = [local.auth.user_pool_arn]
  identity_source = "method.request.header.Authorization"
}

resource "aws_api_gateway_resource" "chat" {
  rest_api_id = aws_api_gateway_rest_api.this.id
  parent_id   = aws_api_gateway_rest_api.this.root_resource_id
  path_part   = "chat"
}

resource "aws_api_gateway_method" "chat" {
  rest_api_id   = aws_api_gateway_rest_api.this.id
  resource_id   = aws_api_gateway_resource.chat.id
  http_method   = "POST"
  authorization = "COGNITO_USER_POOLS"
  authorizer_id = aws_api_gateway_authorizer.cognito.id
}

# STREAM mode invokes the function with InvokeWithResponseStream and forwards bytes as they arrive.
resource "aws_api_gateway_integration" "chat" {
  rest_api_id             = aws_api_gateway_rest_api.this.id
  resource_id             = aws_api_gateway_resource.chat.id
  http_method             = aws_api_gateway_method.chat.http_method
  integration_http_method = "POST"
  type                    = "AWS_PROXY"
  uri                     = aws_lambda_function.chat.response_streaming_invoke_arn
  response_transfer_mode  = "STREAM"
  timeout_milliseconds    = 125000
}

# Browsers send no credentials on a CORS preflight, so OPTIONS has no authorizer and never reaches the Lambda.
resource "aws_api_gateway_method" "preflight" {
  rest_api_id   = aws_api_gateway_rest_api.this.id
  resource_id   = aws_api_gateway_resource.chat.id
  http_method   = "OPTIONS"
  authorization = "NONE"
}

resource "aws_api_gateway_integration" "preflight" {
  rest_api_id = aws_api_gateway_rest_api.this.id
  resource_id = aws_api_gateway_resource.chat.id
  http_method = aws_api_gateway_method.preflight.http_method
  type        = "MOCK"

  request_templates = {
    "application/json" = jsonencode({ statusCode = 200 })
  }
}

resource "aws_api_gateway_method_response" "preflight" {
  rest_api_id = aws_api_gateway_rest_api.this.id
  resource_id = aws_api_gateway_resource.chat.id
  http_method = aws_api_gateway_method.preflight.http_method
  status_code = "200"

  response_parameters = { for name, _ in local.cors_headers : "method.response.header.${name}" => true }
}

resource "aws_api_gateway_integration_response" "preflight" {
  rest_api_id = aws_api_gateway_rest_api.this.id
  resource_id = aws_api_gateway_resource.chat.id
  http_method = aws_api_gateway_method.preflight.http_method
  status_code = aws_api_gateway_method_response.preflight.status_code

  response_parameters = { for name, value in local.cors_headers : "method.response.header.${name}" => value }

  depends_on = [aws_api_gateway_integration.preflight]
}

# Errors raised by API Gateway itself (401 from the authorizer, 403 from the web ACL, 429 from
# throttling) carry the CORS origin so the page can read the status.
resource "aws_api_gateway_gateway_response" "cors" {
  for_each = toset(["DEFAULT_4XX", "DEFAULT_5XX"])

  rest_api_id   = aws_api_gateway_rest_api.this.id
  response_type = each.key

  response_parameters = {
    "gatewayresponse.header.Access-Control-Allow-Origin" = local.cors_headers["Access-Control-Allow-Origin"]
  }
}

resource "aws_api_gateway_deployment" "this" {
  rest_api_id = aws_api_gateway_rest_api.this.id

  triggers = {
    redeployment = sha1(jsonencode([
      aws_api_gateway_resource.chat,
      aws_api_gateway_method.chat,
      aws_api_gateway_integration.chat,
      aws_api_gateway_authorizer.cognito,
      aws_api_gateway_method.preflight,
      aws_api_gateway_integration.preflight,
      aws_api_gateway_method_response.preflight,
      aws_api_gateway_integration_response.preflight,
      aws_api_gateway_gateway_response.cors,
    ]))
  }

  lifecycle {
    create_before_destroy = true
  }
}

resource "aws_cloudwatch_log_group" "api_access" {
  name              = "/${local.name}/api-access"
  retention_in_days = 14
}

# API Gateway writes execution logs to a group with this fixed name. Creating it here sets the
# retention and lets destroy remove it.
resource "aws_cloudwatch_log_group" "api_execution" {
  name              = "API-Gateway-Execution-Logs_${aws_api_gateway_rest_api.this.id}/${local.stage_name}"
  retention_in_days = 14
}

resource "aws_api_gateway_client_certificate" "this" {
  description = "${local.name} ${local.stage_name} stage"
}

resource "aws_api_gateway_stage" "this" {
  rest_api_id           = aws_api_gateway_rest_api.this.id
  deployment_id         = aws_api_gateway_deployment.this.id
  stage_name            = local.stage_name
  xray_tracing_enabled  = true
  client_certificate_id = aws_api_gateway_client_certificate.this.id

  access_log_settings {
    destination_arn = aws_cloudwatch_log_group.api_access.arn
    format = jsonencode({
      requestId    = "$context.requestId"
      requestTime  = "$context.requestTime"
      sourceIp     = "$context.identity.sourceIp"
      user         = "$context.authorizer.claims.sub"
      httpMethod   = "$context.httpMethod"
      resourcePath = "$context.resourcePath"
      status       = "$context.status"
      responseSize = "$context.responseLength"
      latencyMs    = "$context.responseLatency"
      wafStatus    = "$context.waf.status"
      error        = "$context.error.message"
    })
  }

  # The account-level role that lets API Gateway write execution logs is owned by platform/.
  depends_on = [aws_cloudwatch_log_group.api_execution]
}

# Cost guard and execution logging for every method. Request and response bodies are not logged.
resource "aws_api_gateway_method_settings" "all" {
  rest_api_id = aws_api_gateway_rest_api.this.id
  stage_name  = aws_api_gateway_stage.this.stage_name
  method_path = "*/*"

  settings {
    logging_level          = "INFO"
    data_trace_enabled     = false
    metrics_enabled        = true
    throttling_rate_limit  = 2
    throttling_burst_limit = 5
  }
}
