from __future__ import annotations

import uuid
from datetime import UTC, datetime
from typing import Any

from sqlalchemy.orm import Session

from app.models.financial_connector import (
    FinancialConnectorConfig,
    FinancialConnectorConfigEvent,
)


def connector_config_state(row: FinancialConnectorConfig) -> dict[str, Any]:
    """返回可审计的配置状态，刻意排除 secret_ref。"""

    return {
        "id": row.id,
        "tenant_id": row.tenant_id,
        "provider": row.provider,
        "environment": row.environment,
        "key_version": row.key_version,
        "allowed_event_types": sorted(
            str(item) for item in list(row.allowed_event_types_json or [])
        ),
        "clock_skew_seconds": int(row.clock_skew_seconds),
        "status": row.status,
        "version": int(row.version),
    }


def append_connector_config_event(
    db: Session,
    row: FinancialConnectorConfig,
    *,
    action: str,
    actor_id: str,
    request_id: str,
    reason: str,
    expected_version: int | None,
    before: dict[str, Any],
    after: dict[str, Any] | None = None,
) -> FinancialConnectorConfigEvent:
    event = FinancialConnectorConfigEvent(
        id=str(uuid.uuid4()),
        tenant_id=row.tenant_id,
        config_id=row.id,
        action=action,
        actor_id=str(actor_id).strip(),
        request_id=str(request_id).strip(),
        reason=str(reason).strip(),
        expected_version=expected_version,
        before_json=dict(before),
        after_json=dict(after if after is not None else connector_config_state(row)),
        occurred_at=datetime.now(UTC),
    )
    db.add(event)
    return event
