"""Add inquiry close fields + audit trail

Revision ID: 007
Revises: 006
Create Date: 2025-12-15
"""

from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision = '007'
down_revision = '006'
branch_labels = None
depends_on = None


def upgrade() -> None:
    # listing_inquiries: deal workflow
    op.add_column('listing_inquiries', sa.Column('closed_reason', sa.String(200), nullable=True))
    op.add_column('listing_inquiries', sa.Column('closed_at', sa.DateTime(), nullable=True))

    op.create_index(
        'ix_listing_inquiries_listing_created',
        'listing_inquiries',
        ['listing_id', 'created_at'],
        unique=False,
    )
    op.create_index(
        'ix_listing_inquiries_listing_status',
        'listing_inquiries',
        ['listing_id', 'status'],
        unique=False,
    )

    # listing_inquiry_events: audit trail
    op.create_table(
        'listing_inquiry_events',
        sa.Column('id', sa.Integer(), primary_key=True),
        sa.Column('inquiry_id', sa.Integer(), sa.ForeignKey('listing_inquiries.id'), nullable=False, index=True),
        sa.Column('listing_id', sa.Integer(), sa.ForeignKey('domain_listings.id'), nullable=False, index=True),
        sa.Column('actor_user_id', sa.Integer(), sa.ForeignKey('users.id'), nullable=False, index=True),
        sa.Column('old_status', sa.String(20), nullable=True),
        sa.Column('new_status', sa.String(20), nullable=False),
        sa.Column('reason', sa.String(200), nullable=True),
        sa.Column('ip_address', sa.String(45), nullable=True),
        sa.Column('user_agent', sa.String(500), nullable=True),
        sa.Column('created_at', sa.DateTime(), nullable=True, index=True),
    )

    op.create_index(
        'ix_listing_inquiry_events_inquiry_created',
        'listing_inquiry_events',
        ['inquiry_id', 'created_at'],
        unique=False,
    )
    op.create_index(
        'ix_listing_inquiry_events_listing_created',
        'listing_inquiry_events',
        ['listing_id', 'created_at'],
        unique=False,
    )


def downgrade() -> None:
    op.drop_index('ix_listing_inquiry_events_listing_created', table_name='listing_inquiry_events')
    op.drop_index('ix_listing_inquiry_events_inquiry_created', table_name='listing_inquiry_events')
    op.drop_table('listing_inquiry_events')

    op.drop_index('ix_listing_inquiries_listing_status', table_name='listing_inquiries')
    op.drop_index('ix_listing_inquiries_listing_created', table_name='listing_inquiries')
    op.drop_column('listing_inquiries', 'closed_at')
    op.drop_column('listing_inquiries', 'closed_reason')
