"""Add Windows compute node enrollment and registry tables.

Revision ID: 0030
Revises: 0029
Create Date: 2026-08-12
"""

from collections.abc import Sequence

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

revision: str = "0030"
down_revision: str | None = "0029"
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None


def upgrade() -> None:
    op.create_table(
        "compute_node_enrollments",
        sa.Column("enrollment_id", postgresql.UUID(as_uuid=True), primary_key=True),
        sa.Column("code_hash", sa.Text(), nullable=False, unique=True),
        sa.Column("expected_name", sa.Text(), nullable=True),
        sa.Column("allowed_capabilities", postgresql.JSONB(), nullable=False),
        sa.Column("expires_at", sa.DateTime(timezone=True), nullable=False),
        sa.Column("failed_attempts", sa.Integer(), server_default="0", nullable=False),
        sa.Column("consumed_at", sa.DateTime(timezone=True), nullable=True),
        sa.Column(
            "created_by",
            postgresql.UUID(as_uuid=True),
            sa.ForeignKey("users.user_id", ondelete="SET NULL"),
            nullable=True,
        ),
        sa.Column(
            "created_at",
            sa.DateTime(timezone=True),
            server_default=sa.func.now(),
            nullable=False,
        ),
    )
    op.create_table(
        "compute_nodes",
        sa.Column("node_id", postgresql.UUID(as_uuid=True), primary_key=True),
        sa.Column("name", sa.Text(), nullable=False),
        sa.Column(
            "install_id", postgresql.UUID(as_uuid=True), nullable=False, unique=True
        ),
        sa.Column("token_hash", sa.Text(), nullable=False),
        sa.Column("status", sa.Text(), server_default="offline", nullable=False),
        sa.Column("capabilities", postgresql.JSONB(), nullable=False),
        sa.Column("node_version", sa.Text(), server_default="", nullable=False),
        sa.Column("os_version", sa.Text(), server_default="", nullable=False),
        sa.Column("runtime", postgresql.JSONB(), nullable=False),
        sa.Column("last_seen_at", sa.DateTime(timezone=True), nullable=True),
        sa.Column(
            "created_at",
            sa.DateTime(timezone=True),
            server_default=sa.func.now(),
            nullable=False,
        ),
        sa.Column(
            "updated_at",
            sa.DateTime(timezone=True),
            server_default=sa.func.now(),
            nullable=False,
        ),
    )
    op.create_index("ix_compute_nodes_status", "compute_nodes", ["status"])


def downgrade() -> None:
    op.drop_index("ix_compute_nodes_status", table_name="compute_nodes")
    op.drop_table("compute_nodes")
    op.drop_table("compute_node_enrollments")
