"""
Migration: Add exploit_attempts table for tracking exploitation attempts

This migration adds support for tracking which exploits have been attempted,
their outcomes, and related metadata. This enables filtering by attempt status
and provides a historical record of exploitation activities.
"""


def upgrade(db):
    """Create exploit_attempts table."""
    db.execute("""
        CREATE TABLE IF NOT EXISTS exploit_attempts (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            engagement_id INTEGER NOT NULL,
            host_id INTEGER NOT NULL,
            service_id INTEGER,
            exploit_identifier TEXT NOT NULL,
            exploit_title TEXT,
            status TEXT NOT NULL DEFAULT 'not_tried',
            attempted_at TIMESTAMP,
            notes TEXT,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            FOREIGN KEY (engagement_id) REFERENCES engagements(id) ON DELETE CASCADE,
            FOREIGN KEY (host_id) REFERENCES hosts(id) ON DELETE CASCADE,
            FOREIGN KEY (service_id) REFERENCES services(id) ON DELETE SET NULL,
            UNIQUE(engagement_id, host_id, service_id, exploit_identifier)
        )
    """)

    # Create indexes for efficient querying
    db.execute("""
        CREATE INDEX IF NOT EXISTS idx_exploit_attempts_engagement
        ON exploit_attempts(engagement_id)
    """)

    db.execute("""
        CREATE INDEX IF NOT EXISTS idx_exploit_attempts_host
        ON exploit_attempts(host_id)
    """)

    db.execute("""
        CREATE INDEX IF NOT EXISTS idx_exploit_attempts_status
        ON exploit_attempts(status)
    """)

    db.execute("""
        CREATE INDEX IF NOT EXISTS idx_exploit_attempts_identifier
        ON exploit_attempts(exploit_identifier)
    """)


def downgrade(db):
    """Drop exploit_attempts table and indexes."""
    db.execute("DROP INDEX IF EXISTS idx_exploit_attempts_identifier")
    db.execute("DROP INDEX IF EXISTS idx_exploit_attempts_status")
    db.execute("DROP INDEX IF EXISTS idx_exploit_attempts_host")
    db.execute("DROP INDEX IF EXISTS idx_exploit_attempts_engagement")
    db.execute("DROP TABLE IF EXISTS exploit_attempts")
