import uuid
from datetime import datetime
from enum import Enum

from sqlalchemy import DateTime, ForeignKey, String, Uuid, func
from sqlalchemy.orm import Mapped, mapped_column

from app.db.session import Base


class MerchantBusinessType(str, Enum):
    RESTAURANT = "restaurant"
    GROCERY = "grocery"


class Merchant(Base):
    """A merchant brand (e.g. "Wow Burger" or "Fresh Mart"), owned by a
    supplier account. Just a container — location, approval, staff, and
    catalog all live one level down on app.models.branch.Branch, since
    a real business can operate multiple physical branches. A supplier
    may own more than one merchant; an admin can create/manage a
    merchant on a supplier's behalf (owner_id is whichever supplier
    it's for, not necessarily the caller — see
    app.api.v1.endpoints.merchants).

    Kept as its own table rather than folding merchant fields onto
    User (as the legacy schema did — a supplier's login row *was* the
    merchant row) so identity/auth and the business entity aren't
    conflated.

    business_type is the only thing distinguishing a grocery store from
    a restaurant at this level — Branch, MenuCategory, MenuItem, Cart,
    Order, dispatch, pricing, and payment are all deliberately shared
    infrastructure, not duplicated per vertical (matches both the
    legacy schema, which reused one `restaurant` table for grocery
    vendors too, and how comparable platforms like Uber Eats/DoorDash
    structure this: one store/merchant entity with a vertical
    classifier, not a forked catalog). Grocery-only catalog attributes
    (e.g. unit of measure) live on app.models.grocery.GroceryItemDetails,
    a 1:1 extension of MenuItem — MenuItem itself stays untouched.
    Customer-facing listings filter on business_type to show
    "Restaurants" vs "Grocery" separately (see
    app.api.v1.endpoints.merchants.list_merchants).
    """

    __tablename__ = "merchants"

    id: Mapped[uuid.UUID] = mapped_column(Uuid, primary_key=True, default=uuid.uuid4)
    owner_id: Mapped[uuid.UUID] = mapped_column(
        Uuid, ForeignKey("users.id"), nullable=False, index=True
    )
    name: Mapped[str] = mapped_column(String(150), nullable=False)
    description: Mapped[str | None] = mapped_column(String(1000), nullable=True)
    logo_url: Mapped[str | None] = mapped_column(String(500), nullable=True)
    business_type: Mapped[str] = mapped_column(
        String(20), nullable=False, default=MerchantBusinessType.RESTAURANT.value
    )

    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
    )
    deleted_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
