"""
Migration to add expires_at to dispute_attachments.

Public attachment links (public_hash — see add_dispute_attachment_public_hash)
were valid forever with no expiry, so a leaked/forwarded supplier link stayed
live indefinitely. See port log A4.
"""
import logging
from sqlalchemy import text
from database import engine

logger = logging.getLogger(__name__)


async def run_migration():
    """Add expires_at column to dispute_attachments"""
    async with engine.begin() as conn:
        result = await conn.execute(text("""
            SELECT EXISTS (
                SELECT 1 FROM information_schema.columns
                WHERE table_name = 'dispute_attachments'
                AND column_name = 'expires_at'
            );
        """))
        exists = result.scalar()

        if not exists:
            logger.info("Adding 'expires_at' column to dispute_attachments table")
            await conn.execute(text("""
                ALTER TABLE dispute_attachments
                ADD COLUMN IF NOT EXISTS expires_at TIMESTAMP;
            """))
            logger.info("Successfully added 'expires_at' column")
        else:
            logger.info("'expires_at' column already exists in dispute_attachments")
