"""add workspaces table

Revision ID: 2026_06_01_add_workspaces
Revises: 2026_05_29_fix_code_server_bind_addr_port
Create Date: 2026-06-01 10:00:00.000000

"""

from collections.abc import Sequence

from alembic import op
import sqlalchemy as sa

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


def upgrade() -> None:
    # Create workspaces table
    op.create_table(
        "workspaces",
        sa.Column("id", sa.Uuid(as_uuid=True), primary_key=True),
        sa.Column("name", sa.String(255), nullable=False),
        sa.Column(
            "repo_id",
            sa.Uuid(as_uuid=True),
            sa.ForeignKey("git_repositories.id", ondelete="CASCADE"),
            nullable=False,
        ),
        sa.Column(
            "user_id",
            sa.Uuid(as_uuid=True),
            sa.ForeignKey("users.id", ondelete="CASCADE"),
            nullable=False,
        ),
        sa.Column("branch", sa.String(255), nullable=False, server_default="main"),
        sa.Column("path", sa.String(2048), nullable=False),
        sa.Column("status", sa.String(16), nullable=False, server_default="ready"),
        sa.Column("last_sync_at", sa.DateTime(timezone=True), nullable=True),
        sa.Column(
            "created_at",
            sa.DateTime(timezone=True),
            server_default=sa.text("now()"),
            nullable=False,
        ),
        sa.Column(
            "updated_at",
            sa.DateTime(timezone=True),
            server_default=sa.text("now()"),
            nullable=False,
        ),
        sa.UniqueConstraint("repo_id", "name", name="uq_workspace_repo_name"),
        if_not_exists=True,
    )

    op.create_index("idx_workspaces_repo_id", "workspaces", ["repo_id"])
    op.create_index("idx_workspaces_user_id", "workspaces", ["user_id"])
    op.create_index("idx_workspaces_status", "workspaces", ["status"])

    # Add workspace_id to tool_instances
    op.add_column(
        "tool_instances",
        sa.Column(
            "workspace_id",
            sa.Uuid(as_uuid=True),
            sa.ForeignKey("workspaces.id", ondelete="SET NULL"),
            nullable=True,
        ),
    )
    op.create_index(
        "idx_tool_instances_workspace_id", "tool_instances", ["workspace_id"]
    )


def downgrade() -> None:
    op.drop_index("idx_tool_instances_workspace_id", table_name="tool_instances")
    op.drop_column("tool_instances", "workspace_id")
    op.drop_table("workspaces")
