"""Add network_diagrams table.

Revision ID: 074
Revises: 073
Create Date: 2026-04-12
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects.postgresql import UUID, JSONB


revision = "074"
down_revision = "073"
branch_labels = None
depends_on = None

_CURRENT_ACCOUNT = (
    "COALESCE("
    "NULLIF(current_setting('app.current_account_id', TRUE), ''), "
    "'00000000-0000-0000-0000-000000000000'"
    ")::uuid"
)


def upgrade() -> None:
    op.create_table(
        "network_diagrams",
        sa.Column("id", UUID(as_uuid=True), primary_key=True, server_default=sa.text("gen_random_uuid()")),
        sa.Column("account_id", UUID(as_uuid=True), sa.ForeignKey("accounts.id", ondelete="CASCADE"), nullable=False),
        sa.Column("name", sa.String(255), nullable=False),
        sa.Column("client_name", sa.String(255), nullable=True),
        sa.Column("asset_name", sa.String(255), nullable=True),
        sa.Column("description", sa.Text(), nullable=True),
        sa.Column("nodes", JSONB(), nullable=False, server_default=sa.text("'[]'::jsonb")),
        sa.Column("edges", JSONB(), nullable=False, server_default=sa.text("'[]'::jsonb")),
        sa.Column("thumbnail_url", sa.Text(), nullable=True),
        sa.Column("is_archived", sa.Boolean(), nullable=False, server_default=sa.text("false")),
        sa.Column("created_by", UUID(as_uuid=True), sa.ForeignKey("users.id"), nullable=True),
        sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.text("now()")),
        sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.text("now()")),
    )

    op.create_index("ix_network_diagrams_account_id", "network_diagrams", ["account_id"])
    op.create_index("idx_network_diagrams_account_client", "network_diagrams", ["account_id", "client_name"])
    op.execute("ALTER TABLE network_diagrams ENABLE ROW LEVEL SECURITY")
    op.execute("ALTER TABLE network_diagrams FORCE ROW LEVEL SECURITY")
    op.execute(f"""
        CREATE POLICY tenant_isolation ON network_diagrams
        USING (account_id = {_CURRENT_ACCOUNT})
        WITH CHECK (account_id = {_CURRENT_ACCOUNT})
    """)


def downgrade() -> None:
    op.execute("DROP POLICY IF EXISTS tenant_isolation ON network_diagrams")
    op.execute("ALTER TABLE network_diagrams DISABLE ROW LEVEL SECURITY")
    op.drop_table("network_diagrams")
