import uuid
from datetime import datetime

from sqlalchemy import Column, ForeignKey, String
from sqlmodel import Field, SQLModel

from app.db.base import utcnow


class ConversationVerification(SQLModel, table=True):
    """Tracks email OTP verification lifecycle for a conversation.

    One conversation can have multiple verification records (new codes after
    expiry or rate-limit reset).  The relationship is one-to-many from
    Conversation to ConversationVerification.
    """

    __tablename__ = "conversation_verification"

    id: str = Field(default_factory=lambda: str(uuid.uuid4()), primary_key=True)
    conversation_id: str = Field(
        sa_column=Column(
            String,
            ForeignKey("conversation.id", ondelete="CASCADE"),
            index=True,
            nullable=False,
        ),
    )
    email: str = Field(nullable=False)
    code_hash: str = Field(nullable=False)
    created_at: datetime = Field(default_factory=utcnow, nullable=False)
    expires_at: datetime = Field(nullable=False)
    attempts: int = Field(default=0, nullable=False)
    verified_at: datetime | None = Field(default=None, nullable=True)
