"""add_defensive_techniques_tables

Revision ID: b011defensive
Revises: b010threatactors
Create Date: 2026-02-09 16:00:00.000000

"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects.postgresql import UUID


# revision identifiers, used by Alembic.
revision: str = 'b011defensive'
down_revision: Union[str, Sequence[str], None] = 'b010threatactors'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    """Create defensive_techniques and defensive_technique_mappings tables."""
    # defensive_techniques
    op.create_table(
        'defensive_techniques',
        sa.Column('id', UUID(as_uuid=True), primary_key=True),
        sa.Column('d3fend_id', sa.String(), unique=True, nullable=False),
        sa.Column('name', sa.String(), nullable=False),
        sa.Column('description', sa.Text(), nullable=True),
        sa.Column('tactic', sa.String(), nullable=True),
        sa.Column('d3fend_url', sa.String(), nullable=True),
        sa.Column('created_at', sa.DateTime(), server_default=sa.func.now()),
    )
    op.create_index('ix_defensive_techniques_tactic', 'defensive_techniques', ['tactic'])

    # defensive_technique_mappings (ATT&CK → D3FEND)
    op.create_table(
        'defensive_technique_mappings',
        sa.Column('id', UUID(as_uuid=True), primary_key=True),
        sa.Column('attack_technique_id', UUID(as_uuid=True),
                  sa.ForeignKey('techniques.id', ondelete='CASCADE'), nullable=False),
        sa.Column('defensive_technique_id', UUID(as_uuid=True),
                  sa.ForeignKey('defensive_techniques.id', ondelete='CASCADE'), nullable=False),
    )
    op.create_index('ix_dtm_attack_technique', 'defensive_technique_mappings', ['attack_technique_id'])
    op.create_index('ix_dtm_defensive_technique', 'defensive_technique_mappings', ['defensive_technique_id'])
    op.create_unique_constraint('uq_attack_defensive_technique', 'defensive_technique_mappings',
                                ['attack_technique_id', 'defensive_technique_id'])


def downgrade() -> None:
    """Drop defensive_technique_mappings and defensive_techniques tables."""
    op.drop_constraint('uq_attack_defensive_technique', 'defensive_technique_mappings', type_='unique')
    op.drop_index('ix_dtm_defensive_technique', table_name='defensive_technique_mappings')
    op.drop_index('ix_dtm_attack_technique', table_name='defensive_technique_mappings')
    op.drop_table('defensive_technique_mappings')
    op.drop_index('ix_defensive_techniques_tactic', table_name='defensive_techniques')
    op.drop_table('defensive_techniques')
