import uuid
from typing import TYPE_CHECKING

from sqlalchemy import ForeignKey, String, Text
from sqlalchemy import Uuid as UUID
from sqlalchemy.orm import Mapped, mapped_column, relationship

from src.models.base import Base, TimestampMixin, UUIDPrimaryKeyMixin

if TYPE_CHECKING:
    from src.models.project import Project
    from src.models.user import User


class SSHKey(UUIDPrimaryKeyMixin, TimestampMixin, Base):
    __tablename__ = "ssh_keys"

    name: Mapped[str] = mapped_column(String(255))
    public_key: Mapped[str] = mapped_column(Text)
    private_key_encrypted: Mapped[str] = mapped_column(Text)
    user_id: Mapped[uuid.UUID] = mapped_column(UUID(), ForeignKey("users.id"), nullable=False)
    project_id: Mapped[uuid.UUID | None] = mapped_column(UUID(), ForeignKey("projects.id"), nullable=True)

    user: Mapped["User"] = relationship(back_populates="ssh_keys")
    project: Mapped["Project | None"] = relationship(back_populates="ssh_keys", foreign_keys=[project_id])
