import uuid
from datetime import datetime

from sqlalchemy import (
    Boolean,
    CheckConstraint,
    DateTime,
    ForeignKey,
    Integer,
    String,
    Uuid,
    func,
)
from sqlalchemy.orm import Mapped, mapped_column

from app.db.session import Base


class Review(Base):
    """A customer's rating + optional comment on one completed order —
    unique on order_id, so an order can only ever be reviewed once
    (see app.api.v1.endpoints.orders.create_review). branch_id is
    denormalized from the order at creation time (not itself editable)
    purely so branch-level queries — the review listing, and the
    average_rating/review_count rollup on
    app.schemas.branch.BranchOut — don't need to join through orders
    for every read; a branch never changes on an existing order so
    this can't drift.

    supplier_reply/supplier_reply_at are set by the branch's own staff
    (owner/manager/admin — see
    app.api.v1.endpoints.reviews.reply_to_review), a single editable
    reply per review, not a threaded conversation.

    is_hidden is an admin-only moderation flag (see
    app.api.v1.endpoints.reviews.set_review_visibility) — a hidden
    review is excluded from the public listing and the rating rollup,
    but stays in the table for audit rather than being deleted.
    """

    __tablename__ = "reviews"
    __table_args__ = (
        CheckConstraint("rating >= 1 AND rating <= 5", name="ck_reviews_rating_range"),
    )

    id: Mapped[uuid.UUID] = mapped_column(Uuid, primary_key=True, default=uuid.uuid4)
    order_id: Mapped[uuid.UUID] = mapped_column(
        Uuid, ForeignKey("orders.id", ondelete="CASCADE"), unique=True, nullable=False
    )
    customer_id: Mapped[uuid.UUID] = mapped_column(
        Uuid, ForeignKey("users.id"), nullable=False, index=True
    )
    branch_id: Mapped[uuid.UUID] = mapped_column(
        Uuid, ForeignKey("branches.id", ondelete="CASCADE"), nullable=False, index=True
    )

    rating: Mapped[int] = mapped_column(Integer, nullable=False)
    comment: Mapped[str | None] = mapped_column(String(1000), nullable=True)

    supplier_reply: Mapped[str | None] = mapped_column(String(1000), nullable=True)
    supplier_reply_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)

    is_hidden: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)

    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
    )
