"""Create plans table with seed data

Revision ID: 0027
Revises: 0026
Create Date: 2026-06-29
"""
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import postgresql

revision = "0027"
down_revision = "0026"
branch_labels = None
depends_on = None


def upgrade() -> None:
    # ── plans ────────────────────────────────────────────────────────────────
    op.create_table(
        "plans",
        sa.Column(
            "id",
            postgresql.UUID(as_uuid=True),
            primary_key=True,
            server_default=sa.text("gen_random_uuid()"),
        ),
        sa.Column("slug", sa.String(50), nullable=False),
        sa.Column("display_name", sa.String(100), nullable=False),
        sa.Column("price_cad", sa.Numeric(10, 2), nullable=False),
        sa.Column(
            "features",
            postgresql.JSONB(astext_type=sa.Text()),
            nullable=False,
            server_default=sa.text("'[]'::jsonb"),
        ),
        sa.Column(
            "is_popular",
            sa.Boolean,
            nullable=False,
            server_default=sa.text("false"),
        ),
        sa.Column(
            "sort_order",
            sa.Integer,
            nullable=False,
            server_default=sa.text("0"),
        ),
        sa.Column(
            "created_at",
            sa.DateTime(timezone=True),
            nullable=False,
            server_default=sa.text("now()"),
        ),
        sa.Column(
            "updated_at",
            sa.DateTime(timezone=True),
            nullable=False,
            server_default=sa.text("now()"),
        ),
        sa.UniqueConstraint("slug", name="uq_plans_slug"),
    )

    op.create_index("ix_plans_sort_order", "plans", ["sort_order"])

    # ── seed rows ────────────────────────────────────────────────────────────
    # Use op.execute() with explicit JSONB casts so features are stored as
    # JSONB arrays, not JSONB strings (bulk_insert + json.dumps produces the
    # latter because the driver sees a Python str and wraps it in quotes).
    op.execute(
        sa.text("""
        INSERT INTO plans (slug, display_name, price_cad, features, is_popular, sort_order)
        VALUES
            ('starter', 'Starter', 149.00,
             '["Up to 5,000 records","2 staff users","Cemetery map & records","Public memorial pages","Email support"]'::jsonb,
             false, 0),
            ('professional', 'Professional', 349.00,
             '["Up to 25,000 records","10 staff users","Sales, contracts & invoicing","Scheduling calendar","AI search & assist","Priority support"]'::jsonb,
             true, 1),
            ('enterprise', 'Enterprise', 749.00,
             '["Unlimited records","Unlimited staff users","Sales, contracts & invoicing","Scheduling calendar","AI search & assist","Priority support"]'::jsonb,
             false, 2)
        """)
    )


def downgrade() -> None:
    op.drop_index("ix_plans_sort_order", table_name="plans")
    op.drop_table("plans")
