"""Fix tenant_id nullable constraint for tenant-independent subscriptions

This migration fixes the database schema issue where tenant_id was incorrectly
defined as NOT NULL, preventing tenant-independent subscription creation during
registration.

Revision ID: 002_fix_tenant_id_nullable
Revises: 001_unified_initial_schema
Create Date: 2026-01-15 19:00:00.000000+00:00

"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision: str = '002_fix_tenant_id_nullable'
down_revision: Union[str, None] = '001_unified_initial_schema'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    # First, drop the foreign key constraint temporarily
    op.drop_constraint('subscriptions_tenant_id_fkey', 'subscriptions', type_='foreignkey')
    
    # Alter the tenant_id column to be nullable
    op.alter_column('subscriptions', 'tenant_id', 
                   existing_type=sa.UUID(), 
                   nullable=True)
    
    # Recreate the foreign key constraint
    op.create_foreign_key('subscriptions_tenant_id_fkey', 'subscriptions', 'tenants', 
                         ['tenant_id'], ['id'], ondelete='CASCADE')


def downgrade() -> None:
    # Drop the foreign key constraint temporarily
    op.drop_constraint('subscriptions_tenant_id_fkey', 'subscriptions', type_='foreignkey')
    
    # Revert the tenant_id column to be non-nullable
    # Note: This will fail if there are any records with tenant_id = NULL
    op.alter_column('subscriptions', 'tenant_id', 
                   existing_type=sa.UUID(), 
                   nullable=False)
    
    # Recreate the foreign key constraint
    op.create_foreign_key('subscriptions_tenant_id_fkey', 'subscriptions', 'tenants', 
                         ['tenant_id'], ['id'], ondelete='CASCADE')