"""Server model for provisioned infrastructure."""

import uuid
from enum import Enum
from typing import TYPE_CHECKING

from sqlalchemy import ForeignKey, String
from sqlalchemy.orm import Mapped, mapped_column, relationship

from app.models.base import Base, TimestampMixin, UUIDMixin

if TYPE_CHECKING:
    from app.models.tenant import Tenant


class ServerStatus(str, Enum):
    """Server provisioning status."""

    PROVISIONING = "provisioning"
    READY = "ready"
    ERROR = "error"
    TERMINATED = "terminated"


class Server(UUIDMixin, TimestampMixin, Base):
    """
    Server model representing a provisioned VM or container.

    Tracks provisioning state and network configuration.
    """

    __tablename__ = "servers"

    tenant_id: Mapped[uuid.UUID] = mapped_column(
        ForeignKey("tenants.id", ondelete="CASCADE"),
        nullable=False,
        index=True,
    )
    hostname: Mapped[str] = mapped_column(
        String(255),
        nullable=False,
    )
    ip_address: Mapped[str | None] = mapped_column(
        String(45),  # Supports IPv6
        nullable=True,
    )
    status: Mapped[str] = mapped_column(
        String(50),
        default=ServerStatus.PROVISIONING.value,
        nullable=False,
    )

    # Relationships
    tenant: Mapped["Tenant"] = relationship(
        back_populates="servers",
    )

    def __repr__(self) -> str:
        return f"<Server(id={self.id}, hostname={self.hostname}, status={self.status})>"
