import uuid
from datetime import datetime
from enum import Enum

from sqlalchemy import DateTime, Integer, String, Uuid, func
from sqlalchemy.orm import Mapped, mapped_column

from app.db.session import Base


class OTPPurpose(str, Enum):
    SIGNUP = "signup"
    RESET_PIN = "reset_pin"
    ACTIVATE_ACCOUNT = "activate_account"
    ADD_PHONE = "add_phone"
    ADD_EMAIL = "add_email"


class OTPVerification(Base):
    """A one-time code, sent via SMS or email, for signup/PIN reset/
    verifying a phone or email.

    identifier is whichever phone number or email address this
    specific code targets — channel ("sms" or "email") says which one
    it is, and is how it was actually delivered. Signup is now
    single-identifier-first (see
    app.api.v1.endpoints.auth.signup_start): a customer picks phone OR
    email up front, and only that one channel's code ever exists for
    that signup attempt — there's no longer a simultaneous second
    candidate to track, unlike the earlier dual-OTP design this
    replaced. At most one unconsumed code exists per (identifier,
    purpose, channel) — requesting a new one invalidates any earlier
    unconsumed one for that exact combination.
    """

    __tablename__ = "otp_verifications"

    id: Mapped[uuid.UUID] = mapped_column(Uuid, primary_key=True, default=uuid.uuid4)
    identifier: Mapped[str] = mapped_column(String(255), index=True, nullable=False)
    purpose: Mapped[str] = mapped_column(String(20), nullable=False)
    channel: Mapped[str] = mapped_column(String(10), nullable=False, default="sms")
    # Only set for purpose=signup: carries the name through to account
    # creation so the client doesn't have to resend it after verifying.
    pending_name: Mapped[str | None] = mapped_column(String(100), nullable=True)
    code_hash: Mapped[str] = mapped_column(String(255), nullable=False)
    attempts: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
    max_attempts: Mapped[int] = mapped_column(Integer, nullable=False, default=5)
    expires_at: Mapped[datetime] = mapped_column(DateTime, nullable=False)
    consumed_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)

    # Issued once the code above is verified: a short-lived, single-use
    # proof that this identifier was OTP-verified, so the next step
    # (set a PIN / reset a PIN) doesn't need the OTP code resubmitted.
    # Cleared (set to None) once used, so it can't be replayed.
    verification_token_hash: Mapped[str | None] = mapped_column(
        String(64), unique=True, index=True, nullable=True
    )
    verification_token_expires_at: Mapped[datetime | None] = mapped_column(
        DateTime, nullable=True
    )

    created_at: Mapped[datetime] = mapped_column(
        DateTime, server_default=func.now(), nullable=False
    )
