"""billing initial - subscription tiers, addons, billing history

Revision ID: billing_001
Revises: core_001
Create Date: 2026-02-07
"""
import sqlalchemy as sa

from alembic import op

revision = "billing_001"
down_revision = "core_001"
branch_labels = None
depends_on = None


def upgrade() -> None:
    # --- subscription_tiers ---
    op.create_table(
        "subscription_tiers",
        sa.Column("id", sa.Integer(), primary_key=True, index=True),
        sa.Column("platform_id", sa.Integer(), sa.ForeignKey("platforms.id", ondelete="CASCADE"), nullable=True, index=True, comment="Platform this tier belongs to (NULL = global tier)"),
        sa.Column("code", sa.String(30), nullable=False, index=True),
        sa.Column("name", sa.String(100), nullable=False),
        sa.Column("description", sa.Text(), nullable=True),
        sa.Column("price_monthly_cents", sa.Integer(), nullable=False),
        sa.Column("price_annual_cents", sa.Integer(), nullable=True),
        sa.Column("stripe_product_id", sa.String(100), nullable=True),
        sa.Column("stripe_price_monthly_id", sa.String(100), nullable=True),
        sa.Column("stripe_price_annual_id", sa.String(100), nullable=True),
        sa.Column("display_order", sa.Integer(), nullable=True),
        sa.Column("is_active", sa.Boolean(), nullable=False, server_default="true"),
        sa.Column("is_public", sa.Boolean(), nullable=False, server_default="true"),
        sa.Column("created_at", sa.DateTime(), server_default=sa.func.now(), nullable=False),
        sa.Column("updated_at", sa.DateTime(), server_default=sa.func.now(), nullable=False),
    )
    op.create_index("idx_tier_platform_active", "subscription_tiers", ["platform_id", "is_active"])

    # --- store_platforms (depends on subscription_tiers) ---
    op.create_table(
        "store_platforms",
        sa.Column("id", sa.Integer(), primary_key=True, index=True),
        sa.Column("store_id", sa.Integer(), sa.ForeignKey("stores.id", ondelete="CASCADE"), nullable=False, index=True, comment="Reference to the store"),
        sa.Column("platform_id", sa.Integer(), sa.ForeignKey("platforms.id", ondelete="CASCADE"), nullable=False, index=True, comment="Reference to the platform"),
        sa.Column("tier_id", sa.Integer(), sa.ForeignKey("subscription_tiers.id", ondelete="SET NULL"), nullable=True, index=True, comment="Platform-specific subscription tier"),
        sa.Column("is_active", sa.Boolean(), nullable=False, server_default="true", comment="Whether the store is active on this platform"),
        sa.Column("is_primary", sa.Boolean(), nullable=False, server_default="false", comment="Whether this is the store's primary platform"),  # Removed in migration remove_is_primary_001
        sa.Column("custom_subdomain", sa.String(100), nullable=True, comment="Platform-specific subdomain (if different from main subdomain)"),
        sa.Column("settings", sa.JSON(), nullable=True, server_default="{}", comment="Platform-specific store settings"),
        sa.Column("joined_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False, comment="When the store joined this platform"),
        sa.Column("created_at", sa.DateTime(), server_default=sa.func.now(), nullable=False),
        sa.Column("updated_at", sa.DateTime(), server_default=sa.func.now(), nullable=False),
        sa.UniqueConstraint("store_id", "platform_id", name="uq_store_platform"),
    )
    op.create_index("idx_store_platform_active", "store_platforms", ["store_id", "platform_id", "is_active"])
    op.create_index("idx_store_platform_primary", "store_platforms", ["store_id", "is_primary"])  # Removed in migration remove_is_primary_001

    # --- tier_feature_limits ---
    op.create_table(
        "tier_feature_limits",
        sa.Column("id", sa.Integer(), primary_key=True, index=True),
        sa.Column("tier_id", sa.Integer(), sa.ForeignKey("subscription_tiers.id", ondelete="CASCADE"), nullable=False, index=True),
        sa.Column("feature_code", sa.String(80), nullable=False, index=True),
        sa.Column("limit_value", sa.Integer(), nullable=True),
        sa.Column("created_at", sa.DateTime(), server_default=sa.func.now(), nullable=False),
        sa.Column("updated_at", sa.DateTime(), server_default=sa.func.now(), nullable=False),
        sa.UniqueConstraint("tier_id", "feature_code", name="uq_tier_feature_code"),
    )
    op.create_index("idx_tier_feature_lookup", "tier_feature_limits", ["tier_id", "feature_code"])

    # --- addon_products ---
    op.create_table(
        "addon_products",
        sa.Column("id", sa.Integer(), primary_key=True, index=True),
        sa.Column("code", sa.String(50), unique=True, nullable=False, index=True),
        sa.Column("name", sa.String(100), nullable=False),
        sa.Column("description", sa.Text(), nullable=True),
        sa.Column("category", sa.String(50), nullable=False, index=True),
        sa.Column("price_cents", sa.Integer(), nullable=False),
        sa.Column("billing_period", sa.String(20), nullable=False, server_default="monthly"),
        sa.Column("quantity_unit", sa.String(50), nullable=True),
        sa.Column("quantity_value", sa.Integer(), nullable=True),
        sa.Column("stripe_product_id", sa.String(100), nullable=True),
        sa.Column("stripe_price_id", sa.String(100), nullable=True),
        sa.Column("display_order", sa.Integer(), nullable=True),
        sa.Column("is_active", sa.Boolean(), nullable=False, server_default="true"),
        sa.Column("created_at", sa.DateTime(), server_default=sa.func.now(), nullable=False),
        sa.Column("updated_at", sa.DateTime(), server_default=sa.func.now(), nullable=False),
    )

    # --- store_addons ---
    op.create_table(
        "store_addons",
        sa.Column("id", sa.Integer(), primary_key=True, index=True),
        sa.Column("store_id", sa.Integer(), sa.ForeignKey("stores.id"), nullable=False, index=True),
        sa.Column("addon_product_id", sa.Integer(), sa.ForeignKey("addon_products.id"), nullable=False, index=True),
        sa.Column("status", sa.String(20), nullable=False, server_default="active", index=True),
        sa.Column("domain_name", sa.String(255), nullable=True, index=True),
        sa.Column("quantity", sa.Integer(), nullable=False, server_default="1"),
        sa.Column("stripe_subscription_item_id", sa.String(100), nullable=True),
        sa.Column("period_start", sa.DateTime(timezone=True), nullable=True),
        sa.Column("period_end", sa.DateTime(timezone=True), nullable=True),
        sa.Column("cancelled_at", sa.DateTime(timezone=True), nullable=True),
        sa.Column("created_at", sa.DateTime(), server_default=sa.func.now(), nullable=False),
        sa.Column("updated_at", sa.DateTime(), server_default=sa.func.now(), nullable=False),
    )
    op.create_index("idx_store_addon_status", "store_addons", ["store_id", "status"])
    op.create_index("idx_store_addon_product", "store_addons", ["store_id", "addon_product_id"])

    # --- merchant_subscriptions ---
    op.create_table(
        "merchant_subscriptions",
        sa.Column("id", sa.Integer(), primary_key=True, index=True),
        sa.Column("merchant_id", sa.Integer(), sa.ForeignKey("merchants.id", ondelete="CASCADE"), nullable=False, index=True),
        sa.Column("platform_id", sa.Integer(), sa.ForeignKey("platforms.id", ondelete="CASCADE"), nullable=False, index=True),
        sa.Column("tier_id", sa.Integer(), sa.ForeignKey("subscription_tiers.id", ondelete="SET NULL"), nullable=True, index=True),
        sa.Column("status", sa.String(20), nullable=False, server_default="trial", index=True),
        sa.Column("is_annual", sa.Boolean(), nullable=False, server_default="false"),
        sa.Column("period_start", sa.DateTime(timezone=True), nullable=False),
        sa.Column("period_end", sa.DateTime(timezone=True), nullable=False),
        sa.Column("trial_ends_at", sa.DateTime(timezone=True), nullable=True),
        sa.Column("stripe_customer_id", sa.String(100), nullable=True, index=True),
        sa.Column("stripe_subscription_id", sa.String(100), nullable=True, index=True),
        sa.Column("stripe_payment_method_id", sa.String(100), nullable=True),
        sa.Column("payment_retry_count", sa.Integer(), nullable=False, server_default="0"),
        sa.Column("last_payment_error", sa.Text(), nullable=True),
        sa.Column("cancelled_at", sa.DateTime(timezone=True), nullable=True),
        sa.Column("cancellation_reason", sa.Text(), nullable=True),
        sa.Column("created_at", sa.DateTime(), server_default=sa.func.now(), nullable=False),
        sa.Column("updated_at", sa.DateTime(), server_default=sa.func.now(), nullable=False),
        sa.UniqueConstraint("merchant_id", "platform_id", name="uq_merchant_platform_subscription"),
    )
    op.create_index("idx_merchant_sub_status", "merchant_subscriptions", ["merchant_id", "status"])
    op.create_index("idx_merchant_sub_platform", "merchant_subscriptions", ["platform_id", "status"])

    # --- merchant_feature_overrides ---
    op.create_table(
        "merchant_feature_overrides",
        sa.Column("id", sa.Integer(), primary_key=True, index=True),
        sa.Column("merchant_id", sa.Integer(), sa.ForeignKey("merchants.id", ondelete="CASCADE"), nullable=False, index=True),
        sa.Column("platform_id", sa.Integer(), sa.ForeignKey("platforms.id", ondelete="CASCADE"), nullable=False, index=True),
        sa.Column("feature_code", sa.String(80), nullable=False, index=True),
        sa.Column("limit_value", sa.Integer(), nullable=True),
        sa.Column("is_enabled", sa.Boolean(), nullable=False, server_default="true"),
        sa.Column("reason", sa.String(255), nullable=True),
        sa.Column("created_at", sa.DateTime(), server_default=sa.func.now(), nullable=False),
        sa.Column("updated_at", sa.DateTime(), server_default=sa.func.now(), nullable=False),
        sa.UniqueConstraint("merchant_id", "platform_id", "feature_code", name="uq_merchant_platform_feature"),
    )
    op.create_index("idx_merchant_override_lookup", "merchant_feature_overrides", ["merchant_id", "platform_id", "feature_code"])

    # --- stripe_webhook_events ---
    op.create_table(
        "stripe_webhook_events",
        sa.Column("id", sa.Integer(), primary_key=True, index=True),
        sa.Column("event_id", sa.String(100), unique=True, nullable=False, index=True),
        sa.Column("event_type", sa.String(100), nullable=False, index=True),
        sa.Column("status", sa.String(20), nullable=False, server_default="pending", index=True),
        sa.Column("processed_at", sa.DateTime(timezone=True), nullable=True),
        sa.Column("error_message", sa.Text(), nullable=True),
        sa.Column("payload_encrypted", sa.Text(), nullable=True),
        sa.Column("store_id", sa.Integer(), sa.ForeignKey("stores.id"), nullable=True, index=True),
        sa.Column("merchant_subscription_id", sa.Integer(), sa.ForeignKey("merchant_subscriptions.id"), nullable=True, index=True),
        sa.Column("created_at", sa.DateTime(), server_default=sa.func.now(), nullable=False),
        sa.Column("updated_at", sa.DateTime(), server_default=sa.func.now(), nullable=False),
    )
    op.create_index("idx_webhook_event_type_status", "stripe_webhook_events", ["event_type", "status"])

    # --- billing_history ---
    op.create_table(
        "billing_history",
        sa.Column("id", sa.Integer(), primary_key=True, index=True),
        sa.Column("store_id", sa.Integer(), sa.ForeignKey("stores.id"), nullable=True, index=True),
        sa.Column("merchant_id", sa.Integer(), sa.ForeignKey("merchants.id"), nullable=True, index=True),
        sa.Column("stripe_invoice_id", sa.String(100), unique=True, nullable=True, index=True),
        sa.Column("stripe_payment_intent_id", sa.String(100), nullable=True),
        sa.Column("invoice_number", sa.String(50), nullable=True),
        sa.Column("invoice_date", sa.DateTime(timezone=True), nullable=False),
        sa.Column("due_date", sa.DateTime(timezone=True), nullable=True),
        sa.Column("subtotal_cents", sa.Integer(), nullable=False),
        sa.Column("tax_cents", sa.Integer(), nullable=False, server_default="0"),
        sa.Column("total_cents", sa.Integer(), nullable=False),
        sa.Column("amount_paid_cents", sa.Integer(), nullable=False, server_default="0"),
        sa.Column("currency", sa.String(3), nullable=False, server_default="EUR"),
        sa.Column("status", sa.String(20), nullable=False, index=True),
        sa.Column("invoice_pdf_url", sa.String(500), nullable=True),
        sa.Column("hosted_invoice_url", sa.String(500), nullable=True),
        sa.Column("description", sa.Text(), nullable=True),
        sa.Column("line_items", sa.JSON(), nullable=True),
        sa.Column("created_at", sa.DateTime(), server_default=sa.func.now(), nullable=False),
        sa.Column("updated_at", sa.DateTime(), server_default=sa.func.now(), nullable=False),
    )
    op.create_index("idx_billing_store_date", "billing_history", ["store_id", "invoice_date"])
    op.create_index("idx_billing_status", "billing_history", ["store_id", "status"])

    # --- capacity_snapshots ---
    op.create_table(
        "capacity_snapshots",
        sa.Column("id", sa.Integer(), primary_key=True, index=True),
        sa.Column("snapshot_date", sa.DateTime(timezone=True), unique=True, nullable=False, index=True),
        sa.Column("total_stores", sa.Integer(), nullable=False, server_default="0"),
        sa.Column("active_stores", sa.Integer(), nullable=False, server_default="0"),
        sa.Column("trial_stores", sa.Integer(), nullable=False, server_default="0"),
        sa.Column("total_subscriptions", sa.Integer(), nullable=False, server_default="0"),
        sa.Column("active_subscriptions", sa.Integer(), nullable=False, server_default="0"),
        sa.Column("total_products", sa.Integer(), nullable=False, server_default="0"),
        sa.Column("total_orders_month", sa.Integer(), nullable=False, server_default="0"),
        sa.Column("total_team_members", sa.Integer(), nullable=False, server_default="0"),
        sa.Column("storage_used_gb", sa.Numeric(10, 2), nullable=False, server_default="0"),
        sa.Column("db_size_mb", sa.Numeric(10, 2), nullable=False, server_default="0"),
        sa.Column("theoretical_products_limit", sa.Integer(), nullable=True),
        sa.Column("theoretical_orders_limit", sa.Integer(), nullable=True),
        sa.Column("theoretical_team_limit", sa.Integer(), nullable=True),
        sa.Column("tier_distribution", sa.JSON(), nullable=True),
        sa.Column("avg_response_ms", sa.Integer(), nullable=True),
        sa.Column("peak_cpu_percent", sa.Numeric(5, 2), nullable=True),
        sa.Column("peak_memory_percent", sa.Numeric(5, 2), nullable=True),
        sa.Column("created_at", sa.DateTime(), server_default=sa.func.now(), nullable=False),
        sa.Column("updated_at", sa.DateTime(), server_default=sa.func.now(), nullable=False),
    )
    op.create_index("ix_capacity_snapshots_date", "capacity_snapshots", ["snapshot_date"], unique=False)


def downgrade() -> None:
    op.drop_table("capacity_snapshots")
    op.drop_table("billing_history")
    op.drop_table("stripe_webhook_events")
    op.drop_table("merchant_feature_overrides")
    op.drop_table("merchant_subscriptions")
    op.drop_table("store_addons")
    op.drop_table("addon_products")
    op.drop_table("tier_feature_limits")
    op.drop_table("store_platforms")
    op.drop_table("subscription_tiers")
