resource "aws_api_gateway_resource" "fan_response_rest_api_resource" {
  rest_api_id = aws_api_gateway_rest_api.fan_response_rest_api.id
  parent_id   = aws_api_gateway_rest_api.fan_response_rest_api.root_resource_id
  path_part   = local.api_path_part
}

resource "aws_api_gateway_resource" "fan_response_rest_api_sub_resource" {
  rest_api_id = aws_api_gateway_rest_api.fan_response_rest_api.id
  parent_id   = aws_api_gateway_resource.fan_response_rest_api_resource.id
  path_part   = local.api_path_part_sub
}

resource "aws_api_gateway_request_validator" "fan_response_rest_api_validator" {
  name                        = "${local.prefix}-request-validator"
  rest_api_id                 = aws_api_gateway_rest_api.fan_response_rest_api.id
  validate_request_body       = false
  validate_request_parameters = false
}

resource "aws_api_gateway_method" "fan_response_rest_api_method" {
  rest_api_id          = aws_api_gateway_rest_api.fan_response_rest_api.id
  resource_id          = aws_api_gateway_resource.fan_response_rest_api_sub_resource.id
  http_method          = "POST"
  authorization        = "CUSTOM"
  authorizer_id        = aws_api_gateway_authorizer.smf_fan_response_authorizer.id
  request_validator_id = aws_api_gateway_request_validator.fan_response_rest_api_validator.id
}

resource "aws_api_gateway_deployment" "fan_response_rest_api_deployment" {
  rest_api_id = aws_api_gateway_rest_api.fan_response_rest_api.id
  description = "Deployment for Fan Response API Gateway"

  triggers = {
    redeployment = sha1(jsonencode([
      "deploy-triggered-send-definitions-09-07-2025",
      aws_api_gateway_resource.external_root_resource.id,
      aws_api_gateway_resource.email_campaigns_source_resource.id,
      aws_api_gateway_resource.email_campaigns_campaign_id_resource.id,
      aws_api_gateway_resource.email_campaigns_automated_emails_resource.id,
      aws_api_gateway_integration.email_campaigns_automated_emails_integration.id,
    ]))
  }

  lifecycle {
    create_before_destroy = true
  }
}

resource "aws_cloudwatch_log_group" "fan_response_rest_api_log_group" {
  name = "/aws/apigateway/${local.prefix}"

  retention_in_days = 365
  tags              = local.tags
}

resource "aws_api_gateway_client_certificate" "fan_response_rest_api_client_certificate" {
  description = "Client certificate for Fan Response API Gateway"
  tags        = local.tags
}

resource "aws_api_gateway_integration" "fan_response_rest_api_integration" {
  rest_api_id             = aws_api_gateway_rest_api.fan_response_rest_api.id
  resource_id             = aws_api_gateway_resource.fan_response_rest_api_sub_resource.id
  http_method             = aws_api_gateway_method.fan_response_rest_api_method.http_method
  integration_http_method = "POST"
  type                    = "AWS_PROXY"
  uri                     = module.lambda_smf_fan_response.lambda_invoke_arn
}
