"""Add resource_links table for validated DAG parent-child links.

This migration creates the ``resource_links`` table that stores
validated parent-child relationships between resources.  Unlike the
``resource_edges`` table (which stores raw DAG edges with link-type
metadata), ``resource_links`` records relationships that have passed
cycle detection and type compatibility checks.

Revision ID: b1_001_resource_links
Revises: b1_001_resource_registry
Create Date: 2026-02-17 12:00:00

"""

from collections.abc import Sequence

import sqlalchemy as sa
from alembic import op

# revision identifiers, used by Alembic.
revision: str = "b1_001_resource_links"
down_revision: str | Sequence[str] | None = "b1_001_resource_registry"
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None


def upgrade() -> None:
    """Create the resource_links table."""
    op.create_table(
        "resource_links",
        sa.Column(
            "parent_id",
            sa.String(26),
            sa.ForeignKey(
                "resources.resource_id",
                ondelete="CASCADE",
                name="fk_resource_links_parent",
            ),
            nullable=False,
        ),
        sa.Column(
            "child_id",
            sa.String(26),
            sa.ForeignKey(
                "resources.resource_id",
                ondelete="CASCADE",
                name="fk_resource_links_child",
            ),
            nullable=False,
        ),
        sa.Column(
            "created_at",
            sa.String(30),
            nullable=False,
        ),
        sa.PrimaryKeyConstraint("parent_id", "child_id"),
        sa.CheckConstraint(
            "parent_id != child_id",
            name="ck_resource_links_no_self_loop",
        ),
    )

    op.create_index(
        "ix_resource_links_child",
        "resource_links",
        ["child_id"],
        unique=False,
    )
    op.create_index(
        "ix_resource_links_parent",
        "resource_links",
        ["parent_id"],
        unique=False,
    )


def downgrade() -> None:
    """Drop the resource_links table."""
    op.drop_index(
        "ix_resource_links_parent",
        table_name="resource_links",
    )
    op.drop_index(
        "ix_resource_links_child",
        table_name="resource_links",
    )
    op.drop_table("resource_links")
