import uuid
from datetime import datetime
from enum import Enum

from sqlalchemy import Boolean, DateTime, Index, Integer, String, Uuid, func, text
from sqlalchemy.orm import Mapped, mapped_column

from app.db.session import Base


class UserRole(str, Enum):
    CUSTOMER = "customer"
    COURIER = "courier"
    SUPPLIER = "supplier"
    MANAGER = "manager"
    ADMIN = "admin"
    SUPERADMIN = "superadmin"


class User(Base):
    """A Yeneb account.

    Customers self-signup. Courier, supplier, and admin accounts are
    invited by an admin (or superadmin, for other admins); manager
    accounts are invited by a merchant owner (or an admin) to one
    specific branch — that assignment lives in app.models.branch_manager
    .BranchManager, not on this table, since a direct FK column here
    to branches (which itself FKs to merchants, which FKs back to
    users) would create an unresolvable circular foreign-key
    dependency. Every invited person activates their own account by
    SMS OTP and sets their own PIN — see app.api.v1.endpoints.admin,
    app.api.v1.endpoints.branches, and the /auth/activate/* endpoints.
    The very first superadmin exists outside the API entirely, created
    by app.commands.seed_superadmin.

    pin_hash is null between invite and activation: the account exists
    and has a role, but can't log in yet. It's also null for a
    customer created via Google Sign-In who has never set a PIN — that
    account logs in by re-presenting a fresh Google ID token each time
    (see app.api.v1.endpoints.auth.google_signin), not phone+PIN. The
    two null-pin_hash cases are distinguished by google_sub: set for
    the Google case, unset for "invited but not yet activated".

    phone and email are both nullable for the same reason: signup is
    single-identifier-first (see app.api.v1.endpoints.auth.
    signup_start) — a customer picks phone OR email up front, and the
    other is only ever collected later, on request, via /auth/phone/*
    or /auth/email/*, and is entirely skippable. Both phone and email
    are optional on Chapa's own initialize-payment call too (verified
    against Chapa's own docs, not assumed — only amount, currency, and
    tx_ref are required; see app.services.payments.chapa.initialize_payment), so
    Chapa checkout works regardless of which one, if either, is on
    file. Phone only becomes strictly necessary if the customer wants
    an Ethiopian mobile-money channel like Telebirr specifically.
    Courier/supplier/admin/manager accounts always have both in
    practice — admin.py's invite flow still requires them — only the
    customer self-signup and Google Sign-In paths ever leave either one
    null.

    is_phone_verified/is_email_verified track whether we've actually
    proven the account controls that phone/email via OTP (or, for
    email, via Google's own verification) — as opposed to it just
    being a value someone typed. Both are therefore only *uniquely
    enforced* while verified (see the partial unique indexes below, on
    is_phone_verified/is_email_verified) — an unverified value can't
    block the real owner of that phone/email from later using or
    verifying it themselves, on this account or a different one. Only
    a verified identifier can be used to log in (see
    app.api.v1.endpoints.auth.login) or to look an account up for
    forgot-pin, for the same reason. Pre-existing accounts (from
    before this distinction existed) are grandfathered as verified on
    both, since the old signup flow already required real phone OTP
    verification and treated email as globally unique.
    """

    __tablename__ = "users"

    id: Mapped[uuid.UUID] = mapped_column(Uuid, primary_key=True, default=uuid.uuid4)
    phone: Mapped[str | None] = mapped_column(String(20), index=True, nullable=True)
    name: Mapped[str] = mapped_column(String(100), nullable=False)
    email: Mapped[str | None] = mapped_column(String(255), index=True, nullable=True)
    role: Mapped[str] = mapped_column(
        String(20), nullable=False, default=UserRole.CUSTOMER.value
    )
    pin_hash: Mapped[str | None] = mapped_column(String(255), nullable=True)
    google_sub: Mapped[str | None] = mapped_column(
        String(255), unique=True, index=True, nullable=True
    )
    is_phone_verified: Mapped[bool] = mapped_column(
        Boolean, nullable=False, default=False
    )
    is_email_verified: Mapped[bool] = mapped_column(
        Boolean, nullable=False, default=False
    )
    # Opt-in for marketing email (promos, newsletters) — distinct from
    # is_email_verified, which is about proving ownership, not consent
    # to be marketed to. Defaults False: the signup flow presents this
    # as an explicit, unchecked opt-in step, never pre-checked. Set via
    # PATCH /auth/me/marketing-consent.
    marketing_emails_opt_in: Mapped[bool] = mapped_column(
        Boolean, nullable=False, default=False
    )
    is_active: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True)

    failed_pin_attempts: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
    locked_until: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)

    created_at: Mapped[datetime] = mapped_column(
        DateTime, server_default=func.now(), nullable=False
    )
    updated_at: Mapped[datetime] = mapped_column(
        DateTime, server_default=func.now(), onupdate=func.now(), nullable=False
    )

    __table_args__ = (
        Index(
            "ux_users_phone_verified",
            "phone",
            unique=True,
            postgresql_where=text("is_phone_verified = true"),
            sqlite_where=text("is_phone_verified = 1"),
        ),
        Index(
            "ux_users_email_verified",
            "email",
            unique=True,
            postgresql_where=text("is_email_verified = true"),
            sqlite_where=text("is_email_verified = 1"),
        ),
    )
