"""Add inquiry threading (buyer link + messages)

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

from alembic import op
import sqlalchemy as sa


revision = '008'
down_revision = '007'
branch_labels = None
depends_on = None


def upgrade() -> None:
    # Link inquiry to buyer account
    op.add_column('listing_inquiries', sa.Column('buyer_user_id', sa.Integer(), sa.ForeignKey('users.id'), nullable=True))
    op.create_index('ix_listing_inquiries_buyer_user', 'listing_inquiries', ['buyer_user_id'], unique=False)

    # Thread messages
    op.create_table(
        'listing_inquiry_messages',
        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('sender_user_id', sa.Integer(), sa.ForeignKey('users.id'), nullable=False, index=True),
        sa.Column('body', sa.Text(), nullable=False),
        sa.Column('created_at', sa.DateTime(), nullable=True, index=True),
    )

    op.create_index(
        'ix_listing_inquiry_messages_inquiry_created',
        'listing_inquiry_messages',
        ['inquiry_id', 'created_at'],
        unique=False,
    )
    op.create_index(
        'ix_listing_inquiry_messages_listing_created',
        'listing_inquiry_messages',
        ['listing_id', 'created_at'],
        unique=False,
    )
    op.create_index(
        'ix_listing_inquiry_messages_sender_created',
        'listing_inquiry_messages',
        ['sender_user_id', 'created_at'],
        unique=False,
    )


def downgrade() -> None:
    op.drop_index('ix_listing_inquiry_messages_sender_created', table_name='listing_inquiry_messages')
    op.drop_index('ix_listing_inquiry_messages_listing_created', table_name='listing_inquiry_messages')
    op.drop_index('ix_listing_inquiry_messages_inquiry_created', table_name='listing_inquiry_messages')
    op.drop_table('listing_inquiry_messages')

    op.drop_index('ix_listing_inquiries_buyer_user', table_name='listing_inquiries')
    op.drop_column('listing_inquiries', 'buyer_user_id')
