ALTER TABLE agents
  ADD COLUMN IF NOT EXISTS organization_id VARCHAR(40) NOT NULL DEFAULT 'org_system'
    REFERENCES organizations(organization_id);

CREATE INDEX IF NOT EXISTS idx_agents_organization_id ON agents(organization_id);

-- Row-level security: set app.organization_id session variable before queries
-- when multi-tenancy is enforced at the application layer.
-- RLS is enabled but not enforced by default to maintain backward compatibility.
ALTER TABLE agents ENABLE ROW LEVEL SECURITY;

CREATE POLICY agents_org_isolation ON agents
  USING (
    organization_id = COALESCE(
      current_setting('app.organization_id', true),
      'org_system'
    )
  );

-- Allow the policy to be bypassed by superusers / migration scripts
ALTER TABLE agents FORCE ROW LEVEL SECURITY;
