defmodule Towerops.Repo.Migrations.AddIsCloudPollerToAgentTokens do
  use Ecto.Migration

  def change do
    alter table(:agent_tokens) do
      add :is_cloud_poller, :boolean, default: false, null: false
    end

    create index(:agent_tokens, [:is_cloud_poller])

    # Make organization_id nullable for cloud pollers
    execute "ALTER TABLE agent_tokens ALTER COLUMN organization_id DROP NOT NULL",
            "ALTER TABLE agent_tokens ALTER COLUMN organization_id SET NOT NULL"

    # Add check constraint: cloud pollers must have null organization_id
    create constraint(:agent_tokens, :cloud_poller_no_org,
             check:
               "(is_cloud_poller = false AND organization_id IS NOT NULL) OR (is_cloud_poller = true AND organization_id IS NULL)"
           )
  end
end
