import uuid
from datetime import datetime, time
from decimal import Decimal
from enum import Enum

from sqlalchemy import (
    JSON,
    Boolean,
    DateTime,
    Float,
    ForeignKey,
    Numeric,
    String,
    Time,
    Uuid,
    func,
)
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.orm import Mapped, mapped_column

from app.db.session import Base

# Native JSONB on Postgres, plain JSON (TEXT-backed) on SQLite — same
# portability pattern as app.models.menu._JSON_TYPE and
# app.models.delivery._JSON_TYPE.
_JSON_TYPE = JSON().with_variant(JSONB(), "postgresql")

# Monday=0 .. Sunday=6, matching Python's date.weekday() — what
# app.services.branch_hours actually compares working_days against.
# Same convention as app.models.delivery.CourierProfile.working_days.
_ALL_WEEKDAYS = [0, 1, 2, 3, 4, 5, 6]


class BranchApprovalStatus(str, Enum):
    PENDING = "pending"
    APPROVED = "approved"
    REJECTED = "rejected"


class Branch(Base):
    """One physical location of a Merchant — this is the operational
    unit: it has its own address/location, catalog, staff (managers),
    and (eventually) orders. A new branch starts unapproved: an admin
    has to approve it before customers can see it, on top of
    is_active, which the merchant owner/branch manager controls
    day-to-day (open/closed).

    opens_at/closes_at/working_days are an *automatic*, scheduled
    complement to the manual is_active toggle — a branch only actually
    accepts orders right now when BOTH is_active is true AND (no hours
    are set, or the current Addis Ababa wall-clock time falls inside
    them) — see app.services.branch_hours.is_branch_open, the
    enforcement point in app.api.v1.endpoints.cart/orders. opens_at/
    closes_at are nullable and both null by default: a branch with no
    hours set yet is simply never hour-restricted (matches every
    branch's behavior before this feature existed — a new column can
    never retroactively lock existing branches out of orders). Mirrors
    app.models.delivery.CourierProfile's own shift_start/shift_end/
    working_days shape and the same overnight-window handling (e.g.
    20:00-04:00), down to working_days defaulting to every day
    (_ALL_WEEKDAYS) so it stays a no-op restriction until narrowed.
    Unlike a courier's shift, which is admin-only, a branch's own
    owner/manager sets these — it's their business's hours, not an HR
    schedule the platform imposes (see
    app.api.v1.endpoints.branches.update_branch_hours).

    minimum_order_amount is nullable for the same reason (no minimum
    by default, matching every branch's behavior before this feature
    existed) — checked against the cart's item subtotal (before
    delivery fee/service fee/VAT) at checkout, see
    app.api.v1.endpoints.orders.checkout. Set via PATCH
    /branches/{id}/minimum-order.

    latitude/longitude are plain floats rather than a stored PostGIS
    geography column — GeoAlchemy2's Geography type has no SQLite
    fallback, and this project's test suite runs against SQLite, so a
    mapped geography column would break every test in the suite, not
    just this one. Distance-based queries instead cast these floats to
    geography inline at query time (see app.api.v1.endpoints.merchants
    list_branches), which still requires the postgis extension in
    Postgres but keeps the table itself portable and keeps the CRUD
    paths testable without a live PostGIS instance.
    """

    __tablename__ = "branches"

    id: Mapped[uuid.UUID] = mapped_column(Uuid, primary_key=True, default=uuid.uuid4)
    merchant_id: Mapped[uuid.UUID] = mapped_column(
        Uuid,
        ForeignKey("merchants.id", ondelete="CASCADE"),
        nullable=False,
        index=True,
    )
    name: Mapped[str] = mapped_column(String(150), nullable=False)
    address: Mapped[str] = mapped_column(String(255), nullable=False)
    latitude: Mapped[float] = mapped_column(Float, nullable=False)
    longitude: Mapped[float] = mapped_column(Float, nullable=False)
    phone: Mapped[str] = mapped_column(String(20), nullable=False)
    cover_image_url: Mapped[str | None] = mapped_column(String(500), nullable=True)

    approval_status: Mapped[str] = mapped_column(
        String(20), nullable=False, default=BranchApprovalStatus.PENDING.value
    )
    is_active: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True)
    opens_at: Mapped[time | None] = mapped_column(Time, nullable=True)
    closes_at: Mapped[time | None] = mapped_column(Time, nullable=True)
    working_days: Mapped[list[int]] = mapped_column(
        _JSON_TYPE, nullable=False, default=lambda: list(_ALL_WEEKDAYS)
    )
    minimum_order_amount: Mapped[Decimal | None] = mapped_column(
        Numeric(10, 2), 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
    )
    deleted_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
