from django.conf import settings
from django.core.checks import Error, register


@register()
def resource_booking_integration_settings(app_configs, **kwargs):
    errors = []
    config = settings.RESOURCE_BOOKING_INTEGRATION
    if not config.get("DEPLOYMENT_ID"):
        errors.append(Error("RB integration deployment identity is required", id="api.E901"))
    if not config.get("SOURCE_SCOPE"):
        errors.append(Error("RB integration source scope is required", id="api.E908"))
    if config.get("REVERSE_DELIVERY_ENABLED"):
        errors.append(Error("Phase 2 reverse delivery must remain disabled", id="api.E909"))
    if config.get("OCCURRENCE_DST_FOLD") not in {0, 1}:
        errors.append(Error("RB occurrence DST fold must equal 0 or 1", id="api.E918"))
    positive = (
        "PUBLISH_BATCH_SIZE",
        "MAX_ATTEMPTS",
        "RETRY_BASE_SECONDS",
        "RETRY_MAX_SECONDS",
        "CLAIM_TIMEOUT_SECONDS",
        "LOCK_TIMEOUT_MS",
        "STATEMENT_TIMEOUT_MS",
        "PUBLISHER_HEARTBEAT_TIMEOUT_SECONDS",
        "SNAPSHOT_MAX_PAGE_SIZE",
        "SNAPSHOT_MAX_BYTES",
        "MAX_EVENT_BYTES",
        "MAX_EVENTS_PER_CHANGE_SET",
    )
    for key in positive:
        if config.get(key, 0) <= 0:
            errors.append(Error(f"RB integration {key} must be positive", id="api.E902"))
    if config.get("PUBLISH_ENABLED"):
        if not config.get("CAPTURE_ENABLED"):
            errors.append(Error("Enabled RB publisher requires capture", id="api.E910"))
        if not config.get("ACTIVATION_APPROVED"):
            errors.append(Error("Enabled RB publisher requires explicit activation approval", id="api.E911"))
        if config.get("PHASE") != "phase1":
            errors.append(Error("Only the Phase 1 outbound publisher may be enabled", id="api.E912"))
        if config.get("SCHEMA_VERSION") != "2":
            errors.append(Error("Enabled RB publisher requires canonical schema version 2", id="api.E913"))
        if config.get("PUBLISHER_CONCURRENCY") != 1:
            errors.append(Error("Ordered RB publisher concurrency must equal 1", id="api.E914"))
        if not config.get("SNAPSHOT_SERVICE_TOKEN"):
            errors.append(Error("Enabled RB publisher requires snapshot service authentication", id="api.E915"))
        transport = config.get("TRANSPORT", "").lower()
        if transport != "kafka":
            errors.append(Error("Phase 1 RB publisher requires kafka transport", id="api.E903"))
        elif not config.get("KAFKA_TOPIC"):
            errors.append(Error("Enabled Kafka RB publisher requires RB_INTEGRATION_KAFKA_TOPIC", id="api.E904"))
        if not config.get("KAFKA_BOOTSTRAP_SERVERS"):
            errors.append(Error("Enabled Kafka RB publisher requires bootstrap servers", id="api.E919"))
        security_protocol = config.get("KAFKA_SECURITY_PROTOCOL", "").upper()
        if security_protocol not in {"PLAINTEXT", "SSL", "SASL_PLAINTEXT", "SASL_SSL"}:
            errors.append(Error("Unsupported RB Kafka security protocol", id="api.E916"))
        if security_protocol.startswith("SASL") and not all(
            config.get(key)
            for key in ("KAFKA_SASL_MECHANISM", "KAFKA_SASL_USERNAME", "KAFKA_SASL_PASSWORD")
        ):
            errors.append(Error("SASL RB Kafka transport requires mechanism and credentials", id="api.E917"))
    kafka = settings.KAFKA_CONFIG
    if not 0 < kafka["HEARTBEAT_INTERVAL_MS"] < kafka["SESSION_TIMEOUT_MS"] < kafka["MAX_POLL_INTERVAL_MS"]:
        errors.append(
            Error(
                "Kafka heartbeat/session/max-poll values must be strictly increasing",
                id="api.E906",
            )
        )
    if kafka["FETCH_MESSAGE_MAX_BYTES"] <= 0:
        errors.append(Error("Kafka fetch.message.max.bytes must be positive", id="api.E907"))
    return errors
