import uuid
from datetime import time
from decimal import Decimal
from typing import Literal

from pydantic import BaseModel, ConfigDict, field_validator

from app.schemas.menu import MenuCategoryWithItemsOut
from app.utils.phone import InvalidPhoneNumber, normalize_ethiopian_phone


class BranchCreateRequest(BaseModel):
    name: str
    address: str
    latitude: float
    longitude: float
    phone: str
    cover_image_url: str | None = None

    @field_validator("phone")
    @classmethod
    def _phone(cls, v: str) -> str:
        try:
            return normalize_ethiopian_phone(v)
        except InvalidPhoneNumber as exc:
            raise ValueError(str(exc)) from exc

    @field_validator("name", "address")
    @classmethod
    def _not_blank(cls, v: str) -> str:
        v = v.strip()
        if not v:
            raise ValueError("This field is required.")
        return v

    @field_validator("latitude")
    @classmethod
    def _valid_latitude(cls, v: float) -> float:
        if not -90 <= v <= 90:
            raise ValueError("Latitude must be between -90 and 90.")
        return v

    @field_validator("longitude")
    @classmethod
    def _valid_longitude(cls, v: float) -> float:
        if not -180 <= v <= 180:
            raise ValueError("Longitude must be between -180 and 180.")
        return v


class BranchUpdateRequest(BaseModel):
    """Partial — only fields actually sent are changed. Doesn't cover
    approval_status (admin-only, see BranchApproveRequest), opens_at/
    closes_at/working_days (automatic/scheduled, see
    BranchHoursUpdateRequest), or minimum_order_amount (see
    BranchMinimumOrderUpdateRequest) — each already has its own
    dedicated endpoint. is_active is the manual day-to-day open/closed
    switch (see the Branch model docstring) — distinct from the
    scheduled hours, which is_branch_open also factors in."""

    name: str | None = None
    address: str | None = None
    latitude: float | None = None
    longitude: float | None = None
    phone: str | None = None
    cover_image_url: str | None = None
    is_active: bool | None = None

    @field_validator("phone")
    @classmethod
    def _phone(cls, v: str | None) -> str | None:
        if v is None:
            return None
        try:
            return normalize_ethiopian_phone(v)
        except InvalidPhoneNumber as exc:
            raise ValueError(str(exc)) from exc

    @field_validator("name", "address")
    @classmethod
    def _not_blank(cls, v: str | None) -> str | None:
        if v is not None:
            v = v.strip()
            if not v:
                raise ValueError("This field is required.")
        return v

    @field_validator("latitude")
    @classmethod
    def _valid_latitude(cls, v: float | None) -> float | None:
        if v is not None and not -90 <= v <= 90:
            raise ValueError("Latitude must be between -90 and 90.")
        return v

    @field_validator("longitude")
    @classmethod
    def _valid_longitude(cls, v: float | None) -> float | None:
        if v is not None and not -180 <= v <= 180:
            raise ValueError("Longitude must be between -180 and 180.")
        return v


class BranchApproveRequest(BaseModel):
    approval_status: Literal["approved", "rejected"]


class BranchHoursUpdateRequest(BaseModel):
    """Set by the branch's own owner/manager (not an admin-only
    schedule like a courier's shift) — see the Branch model docstring
    on opens_at/closes_at/working_days. All fields optional so a
    caller can narrow working_days without resending hours, or vice
    versa. Pass opens_at/closes_at as null to clear them back to
    "no hour restriction"."""

    opens_at: time | None = None
    closes_at: time | None = None
    working_days: list[int] | None = None

    @field_validator("working_days")
    @classmethod
    def _valid_weekdays(cls, v: list[int] | None) -> list[int] | None:
        if v is not None:
            if not v:
                raise ValueError("working_days can't be empty — use is_active instead.")
            if any(day < 0 or day > 6 for day in v):
                raise ValueError("working_days must be 0 (Monday) through 6 (Sunday).")
            if len(set(v)) != len(v):
                raise ValueError("working_days can't repeat a day.")
        return v


class BranchMinimumOrderUpdateRequest(BaseModel):
    """Set by the branch's own owner/manager, same as hours — see the
    Branch model docstring on minimum_order_amount. Pass null to clear
    it back to "no minimum"."""

    minimum_order_amount: Decimal | None = None

    @field_validator("minimum_order_amount")
    @classmethod
    def _non_negative(cls, v: Decimal | None) -> Decimal | None:
        if v is not None and v < 0:
            raise ValueError("minimum_order_amount can't be negative.")
        return v


class BranchOut(BaseModel):
    model_config = ConfigDict(from_attributes=True)

    id: uuid.UUID
    merchant_id: uuid.UUID
    name: str
    address: str
    latitude: float
    longitude: float
    phone: str
    cover_image_url: str | None
    approval_status: str
    is_active: bool
    opens_at: time | None
    closes_at: time | None
    working_days: list[int]
    minimum_order_amount: Decimal | None
    # Not a Branch column — computed by the endpoint via
    # app.services.branch_hours.is_branch_open, so the client doesn't
    # have to reimplement the Addis-time/working-days/overnight-window
    # logic itself just to show an open/closed badge.
    is_open_now: bool | None = None
    # Not Branch columns either — rolled up from visible (non-hidden)
    # app.models.review.Review rows via
    # app.services.reviews.get_branch_rating_stats. average_rating is
    # null (not 0) when there are no reviews yet, so the client can
    # tell "no reviews" apart from "reviewed and rated 0" (which can't
    # actually happen — ratings are 1-5 — but null still reads more
    # honestly than a fabricated 0.0).
    average_rating: float | None = None
    review_count: int = 0
    # Only populated when the request included a lat/lng to sort by —
    # see app.api.v1.endpoints.merchants.list_branches.
    distance_meters: float | None = None
    # Not a Branch column — whether the current customer has favorited
    # this branch (see app.models.favorite.Favorite). Always False for
    # a non-customer caller (staff/admin/courier can't have favorites)
    # rather than null, since "not favorited" is a meaningful answer
    # for anyone, unlike average_rating's null-means-no-reviews-yet.
    is_favorited: bool = False


class BranchWithMenuOut(BranchOut):
    categories: list[MenuCategoryWithItemsOut] = []
