"""add tool_instances table

Revision ID: 0006_tool_instances
Revises: 0005_ssh_keys_timestamps
Create Date: 2026-05-19 10:00:00.000000

"""
from typing import Sequence, Union

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

# revision identifiers, used by Alembic.
revision: str = "0006_tool_instances"
down_revision: Union[str, None] = "0005_ssh_keys_timestamps"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    op.create_table(
        "tool_instances",
        sa.Column("id", postgresql.UUID(as_uuid=True), server_default=sa.text("gen_random_uuid()"), nullable=False),
        sa.Column("name", sa.String(255), nullable=False),
        sa.Column("display_name", sa.String(255), nullable=False),
        sa.Column("tool_type_id", postgresql.UUID(as_uuid=True), nullable=False),
        sa.Column("repository_id", postgresql.UUID(as_uuid=True), nullable=False),
        sa.Column("project_id", postgresql.UUID(as_uuid=True), nullable=False),
        sa.Column("owner_id", postgresql.UUID(as_uuid=True), nullable=False),
        sa.Column("status", sa.String(50), nullable=False, server_default="pending"),
        sa.Column("container_id", sa.String(255), nullable=True),
        sa.Column("compose_path", sa.String(1024), nullable=True),
        sa.Column("url", sa.String(1024), nullable=True),
        sa.Column("port", sa.Integer(), nullable=True),
        sa.Column("last_started_at", sa.DateTime(timezone=True), nullable=True),
        sa.Column("last_stopped_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.ForeignKeyConstraint(["tool_type_id"], ["tool_types.id"]),
        sa.ForeignKeyConstraint(["repository_id"], ["git_repositories.id"]),
        sa.ForeignKeyConstraint(["project_id"], ["projects.id"]),
        sa.ForeignKeyConstraint(["owner_id"], ["users.id"]),
        sa.PrimaryKeyConstraint("id"),
    )
    op.create_index("idx_tool_instances_owner", "tool_instances", ["owner_id"])
    op.create_index("idx_tool_instances_repo", "tool_instances", ["repository_id"])
    op.create_index("idx_tool_instances_status", "tool_instances", ["status"])


def downgrade() -> None:
    op.drop_index("idx_tool_instances_status", table_name="tool_instances")
    op.drop_index("idx_tool_instances_repo", table_name="tool_instances")
    op.drop_index("idx_tool_instances_owner", table_name="tool_instances")
    op.drop_table("tool_instances")
