from __future__ import annotations

from typing import TYPE_CHECKING
from uuid import UUID

from sqlalchemy import ForeignKey, Index, String, Text
from sqlalchemy.dialects.postgresql import UUID as PG_UUID
from sqlalchemy.orm import Mapped, mapped_column, relationship

from src.database.base import TenantModel

if TYPE_CHECKING:
    from src.apps.support.models.support_ticket import SupportTicket


class SupportTicketMessage(TenantModel):
    """Thread entry for a support ticket (INDL-57).

    The initial ticket description is stored as message #1, created in the
    same transaction as the ticket by SupportTicketService.create(). tenant_id
    is denormalized here (not derived via a join through ticket_id) so
    tenant-isolation queries can filter directly on this table without
    joining back to support_tickets first.
    """

    __tablename__ = "support_ticket_messages"

    __table_args__ = (
        Index("idx_support_messages_ticket_created", "ticket_id", "created_at"),
    )

    # Override tenant_id with explicit FK, matching Record/other tenant models.
    tenant_id: Mapped[UUID] = mapped_column(
        PG_UUID(as_uuid=True),
        ForeignKey("accounts.id", ondelete="CASCADE"),
        nullable=False,
        index=True,
    )

    ticket_id: Mapped[UUID] = mapped_column(
        PG_UUID(as_uuid=True),
        ForeignKey("support_tickets.id", ondelete="CASCADE"),
        nullable=False,
        index=True,
    )
    author_user_id: Mapped[UUID] = mapped_column(
        PG_UUID(as_uuid=True), ForeignKey("users.id"), nullable=False
    )
    author_role_snapshot: Mapped[str] = mapped_column(String(20), nullable=False)
    body: Mapped[str] = mapped_column(Text, nullable=False)

    ticket: Mapped["SupportTicket"] = relationship(back_populates="messages")
