@startuml
title Email Admin JSON Payload Validation (After)

skinparam backgroundColor #FFFFFF
skinparam defaultFontColor #000000
skinparam ArrowColor #000000
skinparam SequenceLifeLineBorderColor #000000
skinparam SequenceLifeLineBackgroundColor #F4F4F4
skinparam ParticipantBorderColor #000000
skinparam ParticipantBackgroundColor #D9EAD3
skinparam NoteBackgroundColor #D9EAD3
skinparam NoteBorderColor #000000

actor "Admin Client" as Client
participant "AdminPlugin\n(/email*, /email-failure*, /email-template*)" as Plugin
participant "Admin Handlers\nnormalize_* + validate_json_value_bounds" as Handlers
participant "Audit Middleware" as Audit
participant "DatabaseAdapter" as DB
database "tenant.sent_emails\ntenant.email_send_failures\ntenant.email_templates" as Tables

Client -> Plugin: POST create/update request\nwith metadata or variables
Plugin -> Handlers: decoded JSON body
Handlers -> Handlers: normalize_metadata_object(...)\nnormalize_template_variables(...)\nvalidate_json_value_bounds(...)

alt invalid metadata/variables
  Handlers --> Plugin: AuthError::bad_request
  Plugin -> Audit: audit_failure_if_needed(...)
  Audit --> Plugin: failure entry persisted
  Plugin --> Client: 4xx
else valid payload
  Handlers -> DB: normalized write payload
  DB -> Tables: INSERT / UPDATE
  Tables --> DB: OK
  DB --> Handlers: OK
  Handlers --> Plugin: success
  Plugin --> Client: 200
end

note right of Handlers
metadata must be JSON object.\nvariables must be unique non-empty strings.\nJSON size/depth limits are enforced.
end note

@enduml
