from app.core.database import get_db_connection, release_db_connection, init_db
import logging

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

def run_migration():
    init_db()  # Initialize the pool
    conn = get_db_connection()
    try:
        with conn.cursor() as cursor:
            # Files linked to a Case
            cursor.execute("""
            CREATE TABLE IF NOT EXISTS sag_files (
                id SERIAL PRIMARY KEY,
                sag_id INTEGER NOT NULL REFERENCES sag_sager(id) ON DELETE CASCADE,
                filename VARCHAR(255) NOT NULL,
                content_type VARCHAR(100),
                size_bytes INTEGER,
                stored_name TEXT NOT NULL,
                uploaded_by_user_id INTEGER REFERENCES users(user_id) ON DELETE SET NULL,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            );
            """)
            
            cursor.execute("CREATE INDEX IF NOT EXISTS idx_sag_files_sag_id ON sag_files(sag_id);")
            cursor.execute("COMMENT ON TABLE sag_files IS 'Files uploaded directly to the Case.';")

            # Emails linked to a Case (Many-to-Many)
            cursor.execute("""
            CREATE TABLE IF NOT EXISTS sag_emails (
                sag_id INTEGER REFERENCES sag_sager(id) ON DELETE CASCADE,
                email_id INTEGER REFERENCES email_messages(id) ON DELETE CASCADE,
                created_at TIMESTAMPTZ DEFAULT NOW(),
                PRIMARY KEY (sag_id, email_id)
            );
            """)

            cursor.execute("COMMENT ON TABLE sag_emails IS 'Emails linked to the Case.';")
            
            conn.commit()
            logger.info("Migration 084 applied successfully.")
    except Exception as e:
        conn.rollback()
        logger.error(f"Migration failed: {e}")
    finally:
        release_db_connection(conn)

if __name__ == "__main__":
    run_migration()
