"""hwadm007: create plans table.

A Plan bundles a pricing template (fee schedule) with a feature plan (feature
access flags) into a single assignable product.  Admins create/manage plans
in the Admin portal; merchants are assigned a plan which drives both what they
pay and what features they can access.

Revision ID: hwadm007_create_plans_table
Revises: hwadm007_billing_revalidation
Create Date: 2026-05-13
"""
from typing import Sequence, Union

import sqlalchemy as sa
from alembic import op

revision: str = "hwadm007_create_plans_table"
down_revision: Union[str, Sequence[str], None] = "hwadm007_billing_revalidation"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    op.create_table(
        "plans",
        sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
        sa.Column("name", sa.String(255), nullable=False),
        sa.Column("description", sa.Text(), nullable=True),
        sa.Column(
            "pricing_template_id",
            sa.Integer(),
            sa.ForeignKey("pricing_templates.id"),
            nullable=False,
        ),
        sa.Column(
            "feature_plan_id",
            sa.Integer(),
            sa.ForeignKey("feature_plans.id"),
            nullable=False,
        ),
        sa.Column(
            "is_active",
            sa.Boolean(),
            nullable=False,
            server_default=sa.true(),
        ),
        sa.Column(
            "created_by_user_id",
            sa.Integer(),
            sa.ForeignKey("users.id"),
            nullable=True,
        ),
        sa.Column(
            "created_at",
            sa.DateTime(timezone=True),
            server_default=sa.text("now()"),
            nullable=False,
        ),
        sa.Column("updated_at", sa.DateTime(timezone=True), nullable=True),
        sa.Column("deleted_at", sa.DateTime(timezone=True), nullable=True),
        sa.PrimaryKeyConstraint("id"),
    )

    # Partial unique index: plan names must be unique among non-deleted rows
    op.create_index(
        "uq_plans_name_active",
        "plans",
        ["name"],
        unique=True,
        postgresql_where=sa.text("deleted_at IS NULL"),
    )

    op.create_index("ix_plans_pricing_template_id", "plans", ["pricing_template_id"])
    op.create_index("ix_plans_feature_plan_id", "plans", ["feature_plan_id"])
    op.create_index("ix_plans_is_active", "plans", ["is_active"])


def downgrade() -> None:
    op.drop_index("ix_plans_is_active", table_name="plans")
    op.drop_index("ix_plans_feature_plan_id", table_name="plans")
    op.drop_index("ix_plans_pricing_template_id", table_name="plans")
    op.drop_index("uq_plans_name_active", table_name="plans")
    op.drop_table("plans")
