"""Let one agent grant span several workspaces, each with its own scopes and spend policy.

Revision ID: 175
Revises: 174

Backfills one row per existing grant from its single-workspace columns, so every
existing connection keeps exactly the access it had. The old agent_grants columns
are left in place (workspace_id stays as the grant's first workspace).
"""
import sqlalchemy as sa
from alembic import op

revision = "175"
down_revision = "174"
branch_labels = None
depends_on = None


def upgrade():
    op.create_table(
        "agent_grant_workspaces",
        sa.Column(
            "grant_id",
            sa.Uuid(),
            sa.ForeignKey("agent_grants.id", ondelete="CASCADE"),
            primary_key=True,
        ),
        sa.Column(
            "workspace_id", sa.Uuid(), sa.ForeignKey("workspaces.id"), primary_key=True
        ),
        sa.Column("scopes", sa.JSON(), nullable=False),
        sa.Column("project_ids", sa.JSON(), nullable=False),
        sa.Column("workspace_wide", sa.Boolean(), nullable=False),
        sa.Column("purchase_policy", sa.JSON(), nullable=False),
        sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
    )
    op.create_index(
        "ix_agent_grant_workspaces_workspace_id", "agent_grant_workspaces", ["workspace_id"]
    )
    op.execute(
        """
        INSERT INTO agent_grant_workspaces
            (grant_id, workspace_id, scopes, project_ids, workspace_wide,
             purchase_policy, created_at)
        SELECT id, workspace_id, scopes, project_ids, workspace_wide, purchase_policy, created_at
        FROM agent_grants
        """
    )


def downgrade():
    op.drop_table("agent_grant_workspaces")
