"""Comprehensive initial schema with all tenant service tables and columns, including coupon tenant_id nullable change

Revision ID: 001_unified_initial_schema
Revises: 
Create Date: 2025-11-06 14:00:00.000000+00:00

"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
from sqlalchemy.dialects.postgresql import UUID
import uuid


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


def upgrade() -> None:
    # Create audit_logs table
    op.create_table('audit_logs',
        sa.Column('id', sa.UUID(), nullable=False),
        sa.Column('tenant_id', sa.UUID(), nullable=False),
        sa.Column('user_id', sa.UUID(), nullable=False),
        sa.Column('action', sa.String(length=100), nullable=False),
        sa.Column('resource_type', sa.String(length=100), nullable=False),
        sa.Column('resource_id', sa.String(length=255), nullable=True),
        sa.Column('severity', sa.String(length=20), nullable=False),
        sa.Column('service_name', sa.String(length=100), nullable=False),
        sa.Column('description', sa.Text(), nullable=True),
        sa.Column('changes', postgresql.JSON(astext_type=sa.Text()), nullable=True),
        sa.Column('audit_metadata', postgresql.JSON(astext_type=sa.Text()), nullable=True),
        sa.Column('ip_address', sa.String(length=45), nullable=True),
        sa.Column('user_agent', sa.Text(), nullable=True),
        sa.Column('endpoint', sa.String(length=255), nullable=True),
        sa.Column('method', sa.String(length=10), nullable=True),
        sa.Column('created_at', sa.DateTime(timezone=True), nullable=False),
        sa.PrimaryKeyConstraint('id')
    )
    op.create_index('idx_audit_resource_type_action', 'audit_logs', ['resource_type', 'action'], unique=False)
    op.create_index('idx_audit_service_created', 'audit_logs', ['service_name', 'created_at'], unique=False)
    op.create_index('idx_audit_severity_created', 'audit_logs', ['severity', 'created_at'], unique=False)
    op.create_index('idx_audit_tenant_created', 'audit_logs', ['tenant_id', 'created_at'], unique=False)
    op.create_index('idx_audit_user_created', 'audit_logs', ['user_id', 'created_at'], unique=False)
    op.create_index(op.f('ix_audit_logs_action'), 'audit_logs', ['action'], unique=False)
    op.create_index(op.f('ix_audit_logs_created_at'), 'audit_logs', ['created_at'], unique=False)
    op.create_index(op.f('ix_audit_logs_resource_id'), 'audit_logs', ['resource_id'], unique=False)
    op.create_index(op.f('ix_audit_logs_resource_type'), 'audit_logs', ['resource_type'], unique=False)
    op.create_index(op.f('ix_audit_logs_service_name'), 'audit_logs', ['service_name'], unique=False)
    op.create_index(op.f('ix_audit_logs_severity'), 'audit_logs', ['severity'], unique=False)
    op.create_index(op.f('ix_audit_logs_tenant_id'), 'audit_logs', ['tenant_id'], unique=False)
    op.create_index(op.f('ix_audit_logs_user_id'), 'audit_logs', ['user_id'], unique=False)

    # Create tenants table
    op.create_table('tenants',
        sa.Column('id', sa.UUID(), nullable=False),
        sa.Column('name', sa.String(length=200), nullable=False),
        sa.Column('subdomain', sa.String(length=100), nullable=True),
        sa.Column('business_type', sa.String(length=100), nullable=True),
        sa.Column('business_model', sa.String(length=100), nullable=True),
        sa.Column('address', sa.Text(), nullable=False),
        sa.Column('city', sa.String(length=100), nullable=True),
        sa.Column('postal_code', sa.String(length=10), nullable=False),
        sa.Column('latitude', sa.Float(), nullable=True),
        sa.Column('longitude', sa.Float(), nullable=True),
        sa.Column('timezone', sa.String(length=50), nullable=False),
        sa.Column('phone', sa.String(length=20), nullable=True),
        sa.Column('email', sa.String(length=255), nullable=True),
        sa.Column('is_active', sa.Boolean(), nullable=True),
        sa.Column('is_demo', sa.Boolean(), nullable=True),
        sa.Column('is_demo_template', sa.Boolean(), nullable=True),
        sa.Column('base_demo_tenant_id', sa.UUID(), nullable=True),
        sa.Column('demo_session_id', sa.String(length=100), nullable=True),
        sa.Column('demo_expires_at', sa.DateTime(timezone=True), nullable=True),
        sa.Column('ml_model_trained', sa.Boolean(), nullable=True),
        sa.Column('last_training_date', sa.DateTime(timezone=True), nullable=True),
        sa.Column('metadata_', sa.JSON(), nullable=True),
        sa.Column('owner_id', sa.UUID(), nullable=False),
        sa.Column('created_at', sa.DateTime(timezone=True), nullable=True),
        sa.Column('updated_at', sa.DateTime(timezone=True), nullable=False, default=sa.text('CURRENT_TIMESTAMP'), onupdate=sa.text('CURRENT_TIMESTAMP')),
        sa.PrimaryKeyConstraint('id'),
        sa.UniqueConstraint('subdomain')
    )
    op.create_index(op.f('ix_tenants_base_demo_tenant_id'), 'tenants', ['base_demo_tenant_id'], unique=False)
    op.create_index(op.f('ix_tenants_demo_session_id'), 'tenants', ['demo_session_id'], unique=False)
    op.create_index(op.f('ix_tenants_is_demo'), 'tenants', ['is_demo'], unique=False)
    op.create_index(op.f('ix_tenants_is_demo_template'), 'tenants', ['is_demo_template'], unique=False)
    op.create_index(op.f('ix_tenants_owner_id'), 'tenants', ['owner_id'], unique=False)

    # Create tenant_members table
    op.create_table('tenant_members',
        sa.Column('id', sa.UUID(), nullable=False),
        sa.Column('tenant_id', sa.UUID(), nullable=False),
        sa.Column('user_id', sa.UUID(), nullable=False),
        sa.Column('role', sa.String(length=50), nullable=True),
        sa.Column('permissions', sa.Text(), nullable=True),
        sa.Column('is_active', sa.Boolean(), nullable=True),
        sa.Column('invited_by', sa.UUID(), nullable=True),
        sa.Column('invited_at', sa.DateTime(timezone=True), nullable=True),
        sa.Column('joined_at', sa.DateTime(timezone=True), nullable=True),
        sa.Column('created_at', sa.DateTime(timezone=True), nullable=False, default=sa.text('CURRENT_TIMESTAMP')),
        sa.ForeignKeyConstraint(['tenant_id'], ['tenants.id'], ondelete='CASCADE'),
        sa.PrimaryKeyConstraint('id')
    )
    op.create_index(op.f('ix_tenant_members_user_id'), 'tenant_members', ['user_id'], unique=False)

    # Create tenant_settings table with current model structure
    op.create_table('tenant_settings',
        sa.Column('id', sa.UUID(), nullable=False),
        sa.Column('tenant_id', sa.UUID(), nullable=False),
        sa.Column('procurement_settings', postgresql.JSON(astext_type=sa.Text()), nullable=False),
        sa.Column('inventory_settings', postgresql.JSON(astext_type=sa.Text()), nullable=False),
        sa.Column('production_settings', postgresql.JSON(astext_type=sa.Text()), nullable=False),
        sa.Column('supplier_settings', postgresql.JSON(astext_type=sa.Text()), nullable=False),
        sa.Column('pos_settings', postgresql.JSON(astext_type=sa.Text()), nullable=False),
        sa.Column('order_settings', postgresql.JSON(astext_type=sa.Text()), nullable=False),
        sa.Column('replenishment_settings', postgresql.JSON(astext_type=sa.Text()), nullable=False),
        sa.Column('safety_stock_settings', postgresql.JSON(astext_type=sa.Text()), nullable=False),
        sa.Column('moq_settings', postgresql.JSON(astext_type=sa.Text()), nullable=False),
        sa.Column('supplier_selection_settings', postgresql.JSON(astext_type=sa.Text()), nullable=False),
        sa.Column('ml_insights_settings', postgresql.JSON(astext_type=sa.Text()), nullable=False),
        sa.Column('created_at', sa.DateTime(timezone=True), nullable=False, default=sa.text('CURRENT_TIMESTAMP')),
        sa.Column('updated_at', sa.DateTime(timezone=True), nullable=False, default=sa.text('CURRENT_TIMESTAMP'), onupdate=sa.text('CURRENT_TIMESTAMP')),
        sa.ForeignKeyConstraint(['tenant_id'], ['tenants.id'], ondelete='CASCADE'),
        sa.PrimaryKeyConstraint('id'),
        sa.UniqueConstraint('tenant_id')
    )

    # Create subscriptions table with all current columns
    op.create_table('subscriptions',
        sa.Column('id', sa.UUID(), nullable=False),
        sa.Column('tenant_id', sa.UUID(), nullable=False),
        sa.Column('plan', sa.String(length=50), nullable=True),
        sa.Column('status', sa.String(length=50), nullable=True),
        sa.Column('monthly_price', sa.Float(), nullable=True),
        sa.Column('billing_cycle', sa.String(length=20), nullable=True),
        sa.Column('next_billing_date', sa.DateTime(timezone=True), nullable=True),
        sa.Column('trial_ends_at', sa.DateTime(timezone=True), nullable=True),
        sa.Column('cancelled_at', sa.DateTime(timezone=True), nullable=True),
        sa.Column('cancellation_effective_date', sa.DateTime(timezone=True), nullable=True),
        sa.Column('stripe_subscription_id', sa.String(255), nullable=True),
        sa.Column('stripe_customer_id', sa.String(255), nullable=True),
        sa.Column('max_users', sa.Integer(), nullable=True),
        sa.Column('max_locations', sa.Integer(), nullable=True),
        sa.Column('max_products', sa.Integer(), nullable=True),
        sa.Column('features', sa.JSON(), nullable=True),
        sa.Column('created_at', sa.DateTime(timezone=True), nullable=False, default=sa.text('CURRENT_TIMESTAMP')),
        sa.Column('updated_at', sa.DateTime(timezone=True), nullable=False, default=sa.text('CURRENT_TIMESTAMP'), onupdate=sa.text('CURRENT_TIMESTAMP')),
        sa.ForeignKeyConstraint(['tenant_id'], ['tenants.id'], ondelete='CASCADE'),
        sa.PrimaryKeyConstraint('id')
    )

    # Create coupons table with tenant_id nullable to support system-wide coupons
    op.create_table('coupons',
        sa.Column('id', sa.UUID(), nullable=False),
        sa.Column('tenant_id', sa.UUID(), nullable=True),  # Changed to nullable to support system-wide coupons
        sa.Column('code', sa.String(length=50), nullable=False),
        sa.Column('discount_type', sa.String(length=20), nullable=False),
        sa.Column('discount_value', sa.Integer(), nullable=False),
        sa.Column('max_redemptions', sa.Integer(), nullable=True),
        sa.Column('current_redemptions', sa.Integer(), nullable=False, default=0),
        sa.Column('valid_from', sa.DateTime(timezone=True), nullable=False),
        sa.Column('valid_until', sa.DateTime(timezone=True), nullable=True),
        sa.Column('active', sa.Boolean(), nullable=False, default=True),
        sa.Column('created_at', sa.DateTime(timezone=True), nullable=False, default=sa.text('CURRENT_TIMESTAMP')),
        sa.Column('extra_data', sa.JSON(), nullable=True),
        sa.ForeignKeyConstraint(['tenant_id'], ['tenants.id'], ondelete='CASCADE'),
        sa.PrimaryKeyConstraint('id'),
        sa.UniqueConstraint('code')  # In the model, it's unique=True on the code column, so per tenant
    )
    op.create_index('idx_coupon_code_active', 'coupons', ['code', 'active'], unique=False)
    op.create_index('idx_coupon_valid_dates', 'coupons', ['valid_from', 'valid_until'], unique=False)
    # Index for tenant_id queries (only non-null values)
    op.create_index('idx_coupon_tenant_id', 'coupons', ['tenant_id'], unique=False)

    # Create coupon_redemptions table with current model structure
    op.create_table('coupon_redemptions',
        sa.Column('id', sa.UUID(), nullable=False),
        sa.Column('tenant_id', sa.String(length=255), nullable=False),
        sa.Column('coupon_code', sa.String(length=50), nullable=False),
        sa.Column('redeemed_at', sa.DateTime(timezone=True), nullable=False, default=sa.text('CURRENT_TIMESTAMP')),
        sa.Column('discount_applied', sa.JSON(), nullable=False),
        sa.Column('extra_data', sa.JSON(), nullable=True),
        sa.ForeignKeyConstraint(['coupon_code'], ['coupons.code'], ),
        sa.PrimaryKeyConstraint('id')
    )
    op.create_index('idx_redemption_tenant', 'coupon_redemptions', ['tenant_id'], unique=False)
    op.create_index('idx_redemption_coupon', 'coupon_redemptions', ['coupon_code'], unique=False)
    op.create_index('idx_redemption_tenant_coupon', 'coupon_redemptions', ['tenant_id', 'coupon_code'], unique=False)

    # Create events table with current model structure
    op.create_table(
        'events',
        sa.Column('id', UUID(as_uuid=True), primary_key=True, default=uuid.uuid4),
        sa.Column('tenant_id', UUID(as_uuid=True), nullable=False, index=True),
        sa.Column('event_name', sa.String(500), nullable=False),
        sa.Column('event_type', sa.String(100), nullable=False, index=True),
        sa.Column('description', sa.Text, nullable=True),
        sa.Column('event_date', sa.Date, nullable=False, index=True),
        sa.Column('start_time', sa.DateTime(timezone=True), nullable=True),
        sa.Column('end_time', sa.DateTime(timezone=True), nullable=True),
        sa.Column('is_all_day', sa.Boolean, default=True),
        sa.Column('expected_impact', sa.String(50), nullable=True),
        sa.Column('impact_multiplier', sa.Float, nullable=True),
        sa.Column('affected_product_categories', sa.String(500), nullable=True),
        sa.Column('location', sa.String(500), nullable=True),
        sa.Column('is_local', sa.Boolean, default=True),
        sa.Column('is_confirmed', sa.Boolean, default=False),
        sa.Column('is_recurring', sa.Boolean, default=False),
        sa.Column('recurrence_pattern', sa.String(200), nullable=True),
        sa.Column('actual_impact_multiplier', sa.Float, nullable=True),
        sa.Column('actual_sales_increase_percent', sa.Float, nullable=True),
        sa.Column('created_at', sa.DateTime(timezone=True), nullable=False, default=sa.text('CURRENT_TIMESTAMP')),
        sa.Column('updated_at', sa.DateTime(timezone=True), nullable=False, default=sa.text('CURRENT_TIMESTAMP'), onupdate=sa.text('CURRENT_TIMESTAMP')),
        sa.Column('created_by', sa.String(255), nullable=True),
        sa.Column('notes', sa.Text, nullable=True),
    )

    # Create event_templates table with current model structure
    op.create_table(
        'event_templates',
        sa.Column('id', UUID(as_uuid=True), primary_key=True, default=uuid.uuid4),
        sa.Column('tenant_id', UUID(as_uuid=True), nullable=False, index=True),
        sa.Column('template_name', sa.String(500), nullable=False),
        sa.Column('event_type', sa.String(100), nullable=False),
        sa.Column('description', sa.Text, nullable=True),
        sa.Column('default_impact', sa.String(50), nullable=True),
        sa.Column('default_impact_multiplier', sa.Float, nullable=True),
        sa.Column('default_affected_categories', sa.String(500), nullable=True),
        sa.Column('recurrence_pattern', sa.String(200), nullable=False),
        sa.Column('is_active', sa.Boolean, default=True),
        sa.Column('created_at', sa.DateTime(timezone=True), nullable=False, default=sa.text('CURRENT_TIMESTAMP')),
        sa.Column('updated_at', sa.DateTime(timezone=True), nullable=False, default=sa.text('CURRENT_TIMESTAMP'), onupdate=sa.text('CURRENT_TIMESTAMP')),
    )

    # Create indexes for better query performance on events
    op.create_index('ix_events_tenant_date', 'events', ['tenant_id', 'event_date'])
    op.create_index('ix_events_type_date', 'events', ['event_type', 'event_date'])
    op.create_index('ix_event_templates_tenant_active', 'event_templates', ['tenant_id', 'is_active'])


def downgrade() -> None:
    # Drop indexes for events
    op.drop_index('ix_event_templates_tenant_active', table_name='event_templates')
    op.drop_index('ix_events_type_date', table_name='events')
    op.drop_index('ix_events_tenant_date', table_name='events')

    # Drop event-related tables
    op.drop_table('event_templates')
    op.drop_table('events')

    # Drop coupon-related tables
    op.drop_index('idx_redemption_tenant_coupon', table_name='coupon_redemptions')
    op.drop_index('idx_redemption_coupon', table_name='coupon_redemptions')
    op.drop_index('idx_redemption_tenant', table_name='coupon_redemptions')
    op.drop_table('coupon_redemptions')

    op.drop_index('idx_coupon_tenant_id', table_name='coupons')
    op.drop_index('idx_coupon_valid_dates', table_name='coupons')
    op.drop_index('idx_coupon_code_active', table_name='coupons')
    op.drop_table('coupons')

    # Drop subscriptions table
    op.drop_table('subscriptions')

    # Drop tenant_settings table
    op.drop_table('tenant_settings')

    # Drop other tables in reverse order
    op.drop_index(op.f('ix_tenant_members_user_id'), table_name='tenant_members')
    op.drop_table('tenant_members')

    op.drop_index(op.f('ix_tenants_owner_id'), table_name='tenants')
    op.drop_index(op.f('ix_tenants_is_demo_template'), table_name='tenants')
    op.drop_index(op.f('ix_tenants_is_demo'), table_name='tenants')
    op.drop_index(op.f('ix_tenants_demo_session_id'), table_name='tenants')
    op.drop_index(op.f('ix_tenants_base_demo_tenant_id'), table_name='tenants')
    op.drop_table('tenants')

    op.drop_index(op.f('ix_audit_logs_user_id'), table_name='audit_logs')
    op.drop_index(op.f('ix_audit_logs_tenant_id'), table_name='audit_logs')
    op.drop_index(op.f('ix_audit_logs_severity'), table_name='audit_logs')
    op.drop_index(op.f('ix_audit_logs_service_name'), table_name='audit_logs')
    op.drop_index(op.f('ix_audit_logs_resource_type'), table_name='audit_logs')
    op.drop_index(op.f('ix_audit_logs_resource_id'), table_name='audit_logs')
    op.drop_index(op.f('ix_audit_logs_created_at'), table_name='audit_logs')
    op.drop_index(op.f('ix_audit_logs_action'), table_name='audit_logs')
    op.drop_index('idx_audit_user_created', table_name='audit_logs')
    op.drop_index('idx_audit_tenant_created', table_name='audit_logs')
    op.drop_index('idx_audit_severity_created', table_name='audit_logs')
    op.drop_index('idx_audit_service_created', table_name='audit_logs')
    op.drop_index('idx_audit_resource_type_action', table_name='audit_logs')
    op.drop_table('audit_logs')