"""Connection models."""

from __future__ import annotations

from datetime import datetime
from typing import Any
from uuid import UUID

from pydantic import BaseModel, ConfigDict


class Connection(BaseModel):
    """A user connection to an MCP server (OAuth, API key, etc.)."""

    model_config = ConfigDict(extra="ignore")

    id: UUID
    user_id: UUID | None = None
    server_id: UUID
    provider_name: str | None = None
    provider_email: str | None = None
    token_type: str = "Bearer"
    expires_at: datetime | None = None
    scopes: list[str] | None = None
    is_valid: bool = True
    health_status: str = "healthy"
    last_refreshed_at: datetime | None = None
    next_refresh_at: datetime | None = None
    consecutive_refresh_failures: int = 0
    refresh_error: str | None = None
    mcp_session_id: str | None = None
    last_accessed_at: datetime | None = None
    created_at: datetime
    updated_at: datetime
    revoked_at: datetime | None = None
    revoke_reason: str | None = None


class ConnectionCreated(BaseModel):
    """Response from creating an API key or bearer connection."""

    model_config = ConfigDict(extra="ignore")

    id: UUID
    server_id: UUID
    user_id: UUID
    credential_type: str
    alias: str | None = None
    header_name: str
    prefix: str = ""
    credential_masked: str
    is_valid: bool = True
    created_at: datetime
    updated_at: datetime


class BasicConnection(BaseModel):
    """Response from creating an HTTP Basic auth connection."""

    model_config = ConfigDict(extra="ignore")

    id: UUID
    server_id: UUID
    user_id: UUID
    username: str
    auth_method: str = "basic"
    connection_data: dict[str, Any] | None = None
    is_valid: bool = True
    created_at: datetime
    updated_at: datetime


class BundleConnection(BaseModel):
    """A connection assigned to a bundle."""

    model_config = ConfigDict(extra="ignore")

    id: UUID
    bundle_id: UUID
    server_id: UUID
    user_connection_id: UUID
    server_name: str
    provider_name: str | None = None
    provider_email: str | None = None
    is_valid: bool = True
    created_at: datetime


class OAuthAuthorization(BaseModel):
    """Response from initiating an OAuth flow."""

    model_config = ConfigDict(extra="ignore")

    authorization_url: str
    state: str
