import uuid
from datetime import datetime
from typing import TYPE_CHECKING

from sqlalchemy import Boolean, DateTime, ForeignKey, String
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 import SSHKey
    from src.models.user import User


class GitRepository(UUIDPrimaryKeyMixin, TimestampMixin, Base):
    __tablename__ = "git_repositories"

    name: Mapped[str] = mapped_column(String(255))
    path: Mapped[str] = mapped_column(String(1024))
    project_id: Mapped[uuid.UUID | None] = mapped_column(UUID(), ForeignKey("projects.id"), nullable=True)
    owner_id: Mapped[uuid.UUID] = mapped_column(UUID(), ForeignKey("users.id"), nullable=False)
    is_mirror: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
    remote_url: Mapped[str | None] = mapped_column(String(1024), nullable=True)
    last_push: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
    ssh_key_id: Mapped[uuid.UUID | None] = mapped_column(
        UUID(), ForeignKey("ssh_keys.id"), nullable=True
    )

    project: Mapped["Project"] = relationship(back_populates="repositories")
    owner: Mapped["User"] = relationship()
    ssh_key: Mapped["SSHKey | None"] = relationship()
