"""add ratings and reviews

Revision ID: 776abe97e67a
Revises: 1209c0afc71a
Create Date: 2026-07-22 10:25:23.214794

"""

from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision: str = "776abe97e67a"
down_revision: Union[str, None] = "1209c0afc71a"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    # NOTE: autogenerate also proposed op.drop_table('spatial_ref_sys')
    # (a PostGIS system table — dropping it would break PostGIS
    # entirely) and dropping refresh_tokens_token_hash_key (recurring,
    # pre-existing unique-index-vs-named-constraint drift unrelated to
    # this migration — same drift called out in 42828b3f2eea). Both
    # removed by hand.
    op.create_table(
        "reviews",
        sa.Column("id", sa.Uuid(), nullable=False),
        sa.Column("order_id", sa.Uuid(), nullable=False),
        sa.Column("customer_id", sa.Uuid(), nullable=False),
        sa.Column("branch_id", sa.Uuid(), nullable=False),
        sa.Column("rating", sa.Integer(), nullable=False),
        sa.Column("comment", sa.String(length=1000), nullable=True),
        sa.Column("supplier_reply", sa.String(length=1000), nullable=True),
        sa.Column("supplier_reply_at", sa.DateTime(), nullable=True),
        sa.Column("is_hidden", sa.Boolean(), nullable=False),
        sa.Column(
            "created_at", sa.DateTime(), server_default=sa.text("now()"), nullable=False
        ),
        sa.Column(
            "updated_at", sa.DateTime(), server_default=sa.text("now()"), nullable=False
        ),
        sa.CheckConstraint(
            "rating >= 1 AND rating <= 5", name="ck_reviews_rating_range"
        ),
        sa.ForeignKeyConstraint(["branch_id"], ["branches.id"], ondelete="CASCADE"),
        sa.ForeignKeyConstraint(
            ["customer_id"],
            ["users.id"],
        ),
        sa.ForeignKeyConstraint(["order_id"], ["orders.id"], ondelete="CASCADE"),
        sa.PrimaryKeyConstraint("id"),
        sa.UniqueConstraint("order_id"),
    )
    op.create_index(
        op.f("ix_reviews_branch_id"), "reviews", ["branch_id"], unique=False
    )
    op.create_index(
        op.f("ix_reviews_customer_id"), "reviews", ["customer_id"], unique=False
    )


def downgrade() -> None:
    op.drop_index(op.f("ix_reviews_customer_id"), table_name="reviews")
    op.drop_index(op.f("ix_reviews_branch_id"), table_name="reviews")
    op.drop_table("reviews")
