"""Add concurrency locks table.

This migration creates the ``locks`` table for plan-level and
project-level concurrency locks with timeout support.

The table stores the lock owner, resource type/id pair, and acquisition
and expiry timestamps.  A unique constraint on (resource_type,
resource_id) ensures at most one active lock per resource.

Revision ID: m4_001_concurrency_locks
Revises: c0_002_merge_skill_registry
Create Date: 2026-02-24 12:00:00

"""

from collections.abc import Sequence

import sqlalchemy as sa
from alembic import op

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


def upgrade() -> None:
    """Create locks table for concurrency control."""
    op.create_table(
        "locks",
        sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
        sa.Column("owner_id", sa.String(255), nullable=False),
        sa.Column("resource_type", sa.String(50), nullable=False),
        sa.Column("resource_id", sa.String(255), nullable=False),
        sa.Column("acquired_at", sa.String(30), nullable=False),
        sa.Column("expires_at", sa.String(30), nullable=False),
        sa.PrimaryKeyConstraint("id"),
        sa.UniqueConstraint(
            "resource_type",
            "resource_id",
            name="uq_locks_resource",
        ),
    )

    op.create_index(
        "ix_locks_owner_id",
        "locks",
        ["owner_id"],
        unique=False,
    )
    op.create_index(
        "ix_locks_expires_at",
        "locks",
        ["expires_at"],
        unique=False,
    )
    op.create_index(
        "ix_locks_resource_type",
        "locks",
        ["resource_type"],
        unique=False,
    )


def downgrade() -> None:
    """Drop locks table."""
    op.drop_index("ix_locks_resource_type", table_name="locks")
    op.drop_index("ix_locks_expires_at", table_name="locks")
    op.drop_index("ix_locks_owner_id", table_name="locks")
    op.drop_table("locks")
